[英]How to convert List<string> to Dictionary<string,string> using linq?
I have a list of strings: 我有一个字符串列表:
List<string> tList=new List<string>();
tList.add("a");
tList.add("mm");
I want to convert this list to a Dictionary so the key and the value of the dictionary is the same using linq 我想将此列表转换为字典,因此使用linq键和键的值是相同的
I have tried: 我努力了:
var dict = tList.ToDictionary<string,string>(m => m, c => c);
but I get the following error: 但是我收到以下错误:
Cannot convert lambda expression to type 'IEqualityComparer' because it is not a delegate type
无法将lambda表达式转换为类型'IEqualityComparer',因为它不是委托类型
Use ToDictionary method: 使用ToDictionary方法:
List<string> tList = new List<string>();
tList.add("a");
tList.add("mm");
var dict = tList.ToDictionary(k => k, v => v);
Do not forget add reference to System.Linq
. 不要忘记添加对
System.Linq
引用。
Here are the signatures for ToDictionary
以下是
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>)
You want the 3rd one, but since you call it and specify two generic types it is instead using the 2nd one and your second argument (actually 3rd since the first is the argument the extension method is called on) is not an IEqualityComparer<TKey>
. 你想要第三个,但是因为你调用它并指定两个泛型类型而是使用第二个和第二个参数(实际上是第三个,因为第一个是调用扩展方法的参数)不是
IEqualityComparer<TKey>
。 The fix is to either specify the third type 修复是指定第三种类型
var dict = tList.ToDictionary<string,string,string>(m => m, c => c);
Don't specify the generic types and let the compiler figure it out via type inference 不要指定泛型类型,让编译器通过类型推断来解决它
var dict = tList.ToDictionary(m => m, c => c);
Or since you want the items to be the values you can just use the 1st one instead and avoid the second lambda altogether. 或者,因为您希望项目是值,您可以使用第一个而不是第二个lambda。
var dict = tList.ToDictionary(c => c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.