字典<StudentType,List <Student >>到IDictionary <StudentType,IList <Student >>?

Ser*_*nov 5 c# dictionary ilist list idictionary

请考虑以下代码:

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);

    ...
}
Run Code Online (Sandbox Code Playgroud)

有错误:

错误CS1503:参数'1':无法从'System.Collections.Generic.Dictionary>'转换为'System.Collections.Generic.IDictionary>'

有没有办法调用foo函数?

Col*_*inE 6

您可以使用Linq ToDictionary方法创建一个新的字典,其值具有正确的类型:

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);
}
Run Code Online (Sandbox Code Playgroud)