Guest User

Untitled

a guest
Jul 17th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. /// <summary>
  2. /// 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.
  3. /// If duplicates keys are present, only the first will be used. Values with duplicate keys will be ignored.
  4. /// </summary>
  5. /// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
  6. /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector" />.</typeparam>
  7. /// <typeparam name="TValue">The type of the value returned by <paramref name="elementSelector" />.</typeparam>
  8. /// <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>
  9. /// <param name="keySelector">A function to extract a key from each element.</param>
  10. /// <param name="elementSelector">A transform function to produce a result element value from each element.</param>
  11. /// <returns>A <see cref="T:System.Collections.Generic.Dictionary`2" /> that contains values of type <paramref name="TValue" /> selected from the input sequence.</returns>
  12. public static Dictionary<TKey, TValue> SafeToDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source,
  13. Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector)
  14. {
  15. source.ThrowIfNullOrEmpty(nameof(source));
  16.  
  17. var dictionary = new Dictionary<TKey, TValue>();
  18. foreach (var key in source.Select(keySelector).Distinct())
  19. {
  20. dictionary.Add(key,
  21. source.Where(p => keySelector(p).Equals(key)).Select(elementSelector).FirstOrDefault());
  22. }
  23.  
  24. return dictionary;
  25. }
Add Comment
Please, Sign In to add comment