与大多数其他答案的问题是,他们使用Distinct
,GroupBy
或者ToLookup
,它的引擎盖下创建一个额外的字典。同样,ToUpper创建额外的字符串。这就是我所做的,几乎是Microsoft代码的完全相同的副本,但有一个更改:
public static Dictionary<TKey, TSource> ToDictionaryIgnoreDup<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null) =>
source.ToDictionaryIgnoreDup(keySelector, i => i, comparer);
public static Dictionary<TKey, TElement> ToDictionaryIgnoreDup<TSource, TKey, TElement>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer = null)
{
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (elementSelector == null)
throw new ArgumentNullException(nameof(elementSelector));
var d = new Dictionary<TKey, TElement>(comparer ?? EqualityComparer<TKey>.Default);
foreach (var element in source)
d[keySelector(element)] = elementSelector(element);
return d;
}
因为在索引器上进行设置会导致它添加密钥,所以它不会抛出,并且只会执行一次密钥查找。您也可以给它一个IEqualityComparer
例如StringComparer.OrdinalIgnoreCase
Dictionary<string, List<Person>>
(或等效)。