如何将List <X>转换为Dictionary <X,Y>将值填充为null?

Neg*_*ion 3 c# linq dictionary list

我试图用List作为键来填充一个Dictionary,并将null作为值.我怎样才能实现这一目标?我在C#编程

谢谢.

McG*_*gle 13

您还可以使用Linq Enumerable.ToDictionary,将键和值指定为null:

var myList = new List<string> { "first", "second" };
Dictionary<string, string> dict = myList.ToDictionary(
    item => item,         // key 
    item => (string)null  // value
);
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将"null"强制转换为元素类型,否则C#无法推断第二个lambda表达式的类型.