C# 通过 lambda 从列表 <> 中删除重复值的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10632776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:35:52  来源:igfitidea点击:

Fastest way to Remove Duplicate Value from a list<> by lambda

c#listc#-4.0lambdageneric-list

提问by Saeid

what is fastest way to remove duplicate values from a list. Assume List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };So I am interesting in use lambda to remove duplicate and returned : {1, 2, 3, 4, 5}. What is your suggestion?

从列表中删除重复值的最快方法是什么。假设List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };所以我很感兴趣使用 lambda 来删除重复项并返回 : {1, 2, 3, 4, 5}。你的建议是什么?

采纳答案by Jon Skeet

The easiest way to get a newlist would be:

获取列表的最简单方法是:

List<long> unique = longs.Distinct().ToList();

Is that good enough for you, or do you need to mutate the existinglist? The latter is significantly more long-winded.

这对你来说足够好,还是你需要改变现有的列表?后者明显更冗长。

Note that Distinct()isn't guaranteedto preserve the original order, but in the current implementation it will - and that's the most naturalimplementation. See my Edulinq blog post about Distinct()for more information.

请注意,Distinct()不能保证保留原始顺序,但在当前实现中会保留 - 这是最自然的实现。有关更多信息,请参阅我的Edulinq 博客文章Distinct()

If you don't need it to be a List<long>, you could just keep it as:

如果您不需要它是 a List<long>,则可以将其保留为:

IEnumerable<long> unique = longs.Distinct();

At this point it will go through the de-duping each time you iterate over uniquethough. Whether that's good or not will depend on your requirements.

此时,每次迭代时它都会进行重复数据删除unique。这是否好取决于您的要求。

回答by Pongsathon.keng

There is Distinct() method. it should works.

有 Distinct() 方法。它应该有效。

List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };
var distinctList = longs.Distinct().ToList();

回答by Nikhil Agrawal

List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();

回答by Wormbo

If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct()extension method does internally, i.e. use a HashSet to check for uniqueness:

如果你想坚持使用原来的 List 而不是创建一个新的 List,你可以使用类似于Distinct()扩展方法在内部所做的事情,即使用 HashSet 来检查唯一性:

HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));

The List class provides this convenient RemoveAll(predicate)method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add()method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.

List 类提供了这种方便的RemoveAll(predicate)方法,可以删除所有不满足谓词指定条件的元素。谓词是一个委托,它接受列表元素类型的参数并返回一个 bool 值。HashSet 的Add()方法仅在集合不包含该项目时才返回 true。因此,通过从列表中删除无法添加到集合中的任何项目,您可以有效地删除所有重复项。

回答by Jon Rea

You can use this extension method for enumerables containing more complex types:

您可以将此扩展方法用于包含更复杂类型的枚举:

IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}

回答by Const Mi

In-place:

到位:

    public static void DistinctValues<T>(List<T> list)
    {
        list.Sort();

        int src = 0;
        int dst = 0;
        while (src < list.Count)
        {
            var val = list[src];
            list[dst] = val;

            ++dst;
            while (++src < list.Count && list[src].Equals(val)) ;
        }
        if (dst < list.Count)
        {
            list.RemoveRange(dst, list.Count - dst);
        }
    }

回答by Moctar Haiz

A simple intuitive implementation

一个简单直观的实现

public static List<PointF> RemoveDuplicates(List<PointF> listPoints)
{
    List<PointF> result = new List<PointF>();

    for (int i = 0; i < listPoints.Count; i++)
    {
        if (!result.Contains(listPoints[i]))
            result.Add(listPoints[i]);
    }

    return result;
}