从List中删除重复项的最有效方法

fub*_*ubo 23 c# list distinct

假设我有一个包含重复值的List,我想删除重复项.

List<int> myList = new List<int>(Enumerable.Range(0, 10000));

// adding a few duplicates here
myList.Add(1); 
myList.Add(2);
myList.Add(3);
Run Code Online (Sandbox Code Playgroud)

我找到了3种方法来解决这个问题:

List<int> result1 = new HashSet<int>(myList).ToList(); //3700 ticks
List<int> result2 = myList.Distinct().ToList(); //4700 ticks
List<int> result3 = myList.GroupBy(x => x).Select(grp => grp.First()).ToList(); //18800 ticks
//referring to pinturic's comment:
List<int> result4 = new SortedSet<int>(myList).ToList(); //18000 ticks
Run Code Online (Sandbox Code Playgroud)

在SO的大多数答案中,Distinct方法显示为"正确的",但HashSet总是更快!

我的问题:当我使用HashSet方法时,有什么我必须要注意的,还有另一种更有效的方法吗?

xan*_*tos 22

这两种方法有很大的不同:

List<int> Result1 = new HashSet<int>(myList).ToList(); //3700 ticks
List<int> Result2 = myList.Distinct().ToList(); //4700 ticks
Run Code Online (Sandbox Code Playgroud)

第一个可以(很可能)改变返回元素的顺序List<>:Result1元素的顺序不会与myList's的顺序相同.第二个保持原始排序.

可能没有比第一个更快的方式.

对于第二个,可能没有"更正确"(对于基于排序的"正确"的某种定义).

(第三个类似于第二个,只是更慢)

出于好奇,这Distinct()是:

// Reference source http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,712
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    return DistinctIterator<TSource>(source, null);
}

// Reference source http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,722
static IEnumerable<TSource> DistinctIterator<TSource>(IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) {
    Set<TSource> set = new Set<TSource>(comparer);
    foreach (TSource element in source)
        if (set.Add(element)) yield return element;
}
Run Code Online (Sandbox Code Playgroud)

因此,最后Distinct()只使用HashSet<>(被调用Set<>)的内部实现来检查项的唯一性.

为了完整起见,我将添加一个问题的链接C#Distinct()方法保持序列的原始排序完整吗?

  • @fubo最后一切都取决于你是否想维持订购. (3认同)