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
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
Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.
Use ToDictionary method:
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
.
Here are the signatures for 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>
. 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.
var dict = tList.ToDictionary(c => c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With