Skip to content

Instantly share code, notes, and snippets.

@donaldgray
Created July 17, 2018 14:03
Show Gist options
  • Save donaldgray/9125d3fc8ff6cbdd6438363cf18ffced to your computer and use it in GitHub Desktop.
Save donaldgray/9125d3fc8ff6cbdd6438363cf18ffced to your computer and use it in GitHub Desktop.
A collection Dictionary Extensions for consuming/creating dictionaries
/// <summary>
/// Creates a <see cref="T:System.Collections.Generic.Dictionary`2" /> from an <see cref="T:System.Collections.Generic.IEnumerable`1" /> according to specified key selector and element selector functions.
/// If duplicates keys are present, only the first will be used. Values with duplicate keys will be ignored.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector" />.</typeparam>
/// <typeparam name="TValue">The type of the value returned by <paramref name="elementSelector" />.</typeparam>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to create a <see cref="T:System.Collections.Generic.Dictionary`2" /> from.</param>
/// <param name="keySelector">A function to extract a key from each element.</param>
/// <param name="elementSelector">A transform function to produce a result element value from each element.</param>
/// <returns>A <see cref="T:System.Collections.Generic.Dictionary`2" /> that contains values of type <paramref name="TValue" /> selected from the input sequence.</returns>
public static Dictionary<TKey, TValue> SafeToDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector)
{
source.ThrowIfNullOrEmpty(nameof(source));
var dictionary = new Dictionary<TKey, TValue>();
foreach (var key in source.Select(keySelector).Distinct())
{
dictionary.Add(key,
source.Where(p => keySelector(p).Equals(key)).Select(elementSelector).FirstOrDefault());
}
return dictionary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment