Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <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;
- }
Add Comment
Please, Sign In to add comment