如何使用linq将List <string>转换为Dictionary <string,string>?

Ala*_*Ala 4 c# linq

我有一个字符串列表:

List<string> tList=new List<string>();
tList.add("a");
tList.add("mm");
Run Code Online (Sandbox Code Playgroud)

我想将此列表转换为字典,因此使用linq键和键的值是相同的

我试过了:

var dict = tList.ToDictionary<string,string>(m => m, c => c);
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

无法将lambda表达式转换为类型'IEqualityComparer',因为它不是委托类型

Bac*_*cks 8

使用ToDictionary方法:

List<string> tList = new List<string>();
tList.add("a");
tList.add("mm");
var dict = tList.ToDictionary(k => k, v => v);
Run Code Online (Sandbox Code Playgroud)

别忘了添加引用System.Linq.


juh*_*arr 5

这是签名 ToDictionary

ToDictionary<TSource, TKey>(
    IEnumerable<TSource>, 
    Func<TSource, TKey>)

ToDictionary<TSource, TKey>(
    IEnumerable<TSource>, 
    Func<TSource, TKey>, 
    IEqualityComparer<TKey>)

ToDictionary<TSource, TKey, TElement>(
    IEnumerable<TSource>, 
    Func<TSource, TKey>, 
    Func<TSource, TElement>)

ToDictionary<TSource, TKey, TElement>(
    IEnumerable<TSource>, 
    Func<TSource, TKey>, 
    Func<TSource, TElement>, 
    IEqualityComparer<TKey>)
Run Code Online (Sandbox Code Playgroud)

您需要第三个参数,但是由于您调用了它并指定了两个泛型类型,因此它使用的是第二个参数,而您的第二个参数(实际上是第三个参数,因为第一个是调用扩展方法的参数)不是IEqualityComparer<TKey>。解决方法是指定第三个类型

var dict = tList.ToDictionary<string,string,string>(m => m, c => c);
Run Code Online (Sandbox Code Playgroud)

不要指定泛型类型,而让编译器通过类型推断来解决

var dict = tList.ToDictionary(m => m, c => c);
Run Code Online (Sandbox Code Playgroud)

或者,由于您希望这些项目成为值,因此可以只使用第一个,而完全避免第二个lambda。

var dict = tList.ToDictionary(c => c);
Run Code Online (Sandbox Code Playgroud)