If the ElementSelector is not specified, the element
itself is considered as a value by default.
Chapter 7
[ 195 ]
Following is an example for creating the dictionary from the list of items:
List
items = GetItems();
Dictionary icecreamNames = items.
ToDictionary(itm => itm.Name);
Console.WriteLine("ToDictionary Example: ");
foreach (KeyValuePair ice in icecreamNames)
Console.WriteLine("Key:{0}, Name:{1}", ice.Key,
ice.Value.Ingredients);
In the above example, items is a list that contains a list of Icecreams objects that
have different properties such as name, category, ingredients, price, etc. Here,
KeySelector is a string which is the key for the dictionary, and the object Icecreams
itself is the element. The resultant dictionary has the item name as a key and the
Item itself as a value.
An ArgumentNullException is thrown if the source, KeySelector,
ElementSelector, or the key itself produced by the KeySelector is null. An
ArgumentException is thrown if the KeySelector returns the same key for two
elements.
Pages:
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294