C# Enumerable ToDictionary(IEnumerable, Func)
Description
Creates a Dictionary from an IEnumerable according to a specified key selector function.
Syntax
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
Parameters
TSource
- The type of the elements of source.TKey
- The type of the key returned by keySelector.source
- An IEnumerable to create a Dictionaryfrom.keySelector
- A function to extract a key from each element.
Example
The following code example demonstrates how to use ToDictionary to create a Dictionary by using a key selector.
/*from ww w . j a v a2s .co m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
List<Package> packages =new List<Package>
{ new Package { Company = "A", Weight = 25.2, TrackingNumber = 12L },
new Package { Company = "B", Weight = 18.7, TrackingNumber = 55L },
new Package { Company = "C", Weight = 6.0, TrackingNumber = 22L },
new Package { Company = "D", Weight = 33.8, TrackingNumber = 73L } };
Dictionary<long, Package> dictionary =packages.ToDictionary(p => p.TrackingNumber);
foreach (KeyValuePair<long, Package> kvp in dictionary)
{
Console.WriteLine(
"Key {0}: {1}, {2} pounds",
kvp.Key,
kvp.Value.Company,
kvp.Value.Weight);
}
}
}
class Package{
public string Company { get; set; }
public double Weight { get; set; }
public long TrackingNumber { get; set; }
}
The code above generates the following result.