{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The ToDictionary operator creates a Dictionary from a sequence.
EditMethod Signatures
// 1 - Creates a dictionary (one key & value dictionary entry per element) from a sequence.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
// 2 - Create a dictionary from a sequence using a custom comparer.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
// 3 - Create a dictionary from a sequence of new elements.
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector)
// 4 - Create a dictionary from a sequence of new elements using a custom comparer.
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
Ithis Enumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer)EditExceptions
Throws an ArgumentNullException if
source,
keySelector, or
elementSelector are null.
EditPseudo-code
Overload 1
Set comparer to
EqualityComparer<TSource>.Default).
Set element selector the be the TSource instance.
Call and return the result of Overload 4 passing in
source,
keySelector, element selector and comparer.
Overload 2
Set element selector the be the TSource instance.
Call and return the result of Overload 4 passing in
source,
keySelector, element selector and
comparer.
Overload 3
Set comparer to
EqualityComparer<TSource>.Default).
Call and return the result of Overload 4 passing in
source,
keySelector,
elementSelector and comparer.
Overload 4
If
source is null, throw an ArgumentNullException.
If
keySelector is null, throw an ArgumentNullException.
If
elementSelector is null, throw an ArgumentNullException.
Create a
Dictionary<TKey,TSource> instance, passing in
comparer.
Iterate the
source sequence.
Call dictionary.Add(keySelector(current element), elementSelector(current element));
Return the dictionary.
EditLoop Count
1. The
source sequence is enumerated once and elements are added to a dictionary.
EditCode Samples
XElement Example
The following code sample shows a LINQ query that returns all XElement objects matching a tag name, and then makes a dictionary out of them. The key in the dictionary is the "key" Attribute on the XElement and the value on the dictionary is the Value property.
var displayDict = (from name in _x.Elements("CategoryName")
select name).ToDictionary(n => n.Attribute("key").Value, n => n.Value);ToDictionary Lambda Expression article.