Ala
Ala

Reputation: 1503

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

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

Upvotes: 5

Views: 10499

Answers (2)

juharr
juharr

Reputation: 32296

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);

Upvotes: 5

Backs
Backs

Reputation: 24913

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.

Upvotes: 12

Related Questions