5

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

2
  • 2
    What have you tried to do to solve this problem, and what problems have you had with your attempted solutions? Commented Sep 10, 2015 at 14:51
  • @Servy I have updated my question :) Commented Sep 10, 2015 at 14:56

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For the life of me, could not figure out what I was doing wrong in my code. I was doing basically as above, but had specified the type parameters for ToDictionary like this: ` var dict = tList.ToDictionary<string, string>(k => k, v => v); ` The trick was to remove those type parameters as this answer shows: ` var dict = tList.ToDictionary(k => k, v => v); `
5

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

1 Comment

I appreciate the clear explanation, it made me realize I could use ToDictionary<string,string,object> to create a Dictionary<string,object>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.