Search code examples
c#listdictionaryilistidictionary

Dictionary<StudentType, List<Student>> to IDictionary<StudentType, IList<Student>>?


Please consider the following code:

class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{   
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict = 
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}

There is the error:

error CS1503: Argument '1': cannot convert from 'System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.IDictionary>'

Is there any way to call foo function?


Solution

  • You could use the Linq ToDictionary method to create a new dictionary where the value has the correct type:

    static void Main(string[] args)
    {
      Dictionary<StudentType, List<Student>> studentDict = new Dictionary<StudentType, List<Student>>();
      var dicTwo = studentDict.ToDictionary(item => item.Key, item => (IList<Student>)item.Value);
      foo(dicTwo);
    }