Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<string> to Dictionary<string,string> using linq?

Tags:

c#

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

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

like image 445
Ala Avatar asked Sep 10 '15 14:09

Ala


People also ask

Can we convert list to dictionary in C#?

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.


2 Answers

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.

like image 190
Backs Avatar answered Oct 24 '22 16:10

Backs


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);
like image 35
juharr Avatar answered Oct 24 '22 14:10

juharr