using System.Collections;
using System.Collections.Generic;
public static void Main()
var goodCollection = new[] {"0","1","2","3"};
var badCollection = new[] {"1","1","2","3"};
Console.Write("goodCollection.ToDictionary");
goodCollection.ToDictionary(x=>x, y=>y);
Console.WriteLine(" works");
}catch {Console.WriteLine(" not work");}
Console.Write("badCollection.ToDictionary");
badCollection.ToDictionary(x=>x, y=>y);
Console.WriteLine(" works");
}catch {Console.WriteLine(" not work");}
Console.Write("goodCollection.ToDictionarySafe");
goodCollection.ToDictionarySafe(x=>x, y=>y);
Console.WriteLine(" works");
}catch {Console.WriteLine(" not work");}
Console.Write("badCollection.ToDictionarySafe");
badCollection.ToDictionarySafe(x=>x, y=>y);
Console.WriteLine(" works");
}catch {Console.WriteLine(" not work");}
public static class EnumerableExtensions
public static Dictionary<TKey, TElement> ToDictionarySafe<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer = null)
var dictionary = new Dictionary<TKey, TElement>(comparer);
foreach (TSource element in source)
dictionary[keySelector(element)] = elementSelector(element);
public static Dictionary<TDest, TDest> ToDictionarySafe<TSource, TDest>(
this IEnumerable<TSource> source,
Func<TSource, TDest> selector,
IEqualityComparer<TDest> comparer = null)
var dictionary = new Dictionary<TDest, TDest>(comparer);
foreach (TSource element in source)
var selectedElement = selector(element);
dictionary[selectedElement] = selectedElement;