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

Pay attention to 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);

    ...
}

An error occurred:

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

Is there a way to call the foo function?

+5
source share
3 answers

You can use the Linq ToDictionary method to create a new dictionary, where the value is of 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);
}
+6
source

You will have a new dictionary with the correct types, copying data from the old to the new.

.

, , .

:

  • Student
  • , IStudent
  • , , , ,
+3

change studentDict creation:

Dictionary<StudentType, IList<Student>> studentDict = new Dictionary<StudentType, IList<Student>>();
0
source

All Articles