Skip to content

Instantly share code, notes, and snippets.

@IEvangelist
Last active August 23, 2019 12:37
Show Gist options
  • Save IEvangelist/040583155fd714210bb88450d7bae870 to your computer and use it in GitHub Desktop.
Save IEvangelist/040583155fd714210bb88450d7bae870 to your computer and use it in GitHub Desktop.
public static Dictionary<TKey, TElement> ToDistinctDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer)
{
if (source is null) throw new ArgumentNullException(nameof(source));
if (keySelector is null) throw new ArgumentNullException(nameof(keySelector));
if (elementSelector is null) throw new ArgumentNullException(nameof(elementSelector));
var dictionary = new Dictionary<TKey, TElement>(comparer ?? Comparer<TKey>.Default);
foreach (var element in source)
{
dictionary[keySelector(element)] = elementSelector(element);
}
return dictionary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment