Reputation: 6979
To convert a list to a dictionary, we can do it easily with the follwing:
list.ToDictionary(v=> v, v=>true);
For the first parameter in ToDictionary
, I can understand the first parameter is the element of the dictionary. But what is meant by v=> true
?
The second parameter should be of the type IEqualityComparer
. What purpose does this serve? How is v=> true
same as IEqualityComparer
?
Upvotes: 0
Views: 1415
Reputation: 1911
When your list has [1,2,3,4] and you convert it to a dictionary by list.ToDictionary(v=> v, v=>true);
then your dictionary has this values
[1,true]
[2,true]
[3,true]
[4,true].
The first value is the key the second is the value
EDIT:
just as @dkson said the second parameter is an elementSelector. You can see this in intellisense when you go to the 3rd of 4 entries :)
Upvotes: 1
Reputation: 101142
This is the method is used.
The second parameter (v => true) is the elementSelector (A transform function to produce a result element value from each element).
A list with the elements 1
, 2
and 3
would result in a dictionary with the following mapping (all values are true
):
1: true
2: true
3: true
Upvotes: 1
Reputation: 38142
You Take a look at the MSDN documentation. This is the overload taking a second IEqualityComparer
argument:
ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IEqualityComparer<TKey>)
However, in your example you are using the overload which takes a Func<TSource, TElement>
which is responsible for generating the values of the dictionary:
ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>)
(In your case, all values are simply true
)
Upvotes: 1