C# LINQ在List中查找重复项

513
使用LINQ,从一个List<int>中,如何检索包含多个重复条目及其值的列表?
13个回答

1

Linq查询:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;

0

所有的GroupBy答案都是最简单的,但不会是最有效率的。它们对于内存性能特别差,因为构建大型内部集合具有分配成本。

一个不错的替代方案是HuBeZa的基于HashSet.Add的方法。它的性能更好。

如果您不关心空值,我认为像这样的方法是最有效率的(无论是CPU还是内存):

public static IEnumerable<TProperty> Duplicates<TSource, TProperty>(
    this IEnumerable<TSource> source,
    Func<TSource, TProperty> duplicateSelector,
    IEqualityComparer<TProperty> comparer = null)
{
    comparer ??= EqualityComparer<TProperty>.Default;

    Dictionary<TProperty, int> counts = new Dictionary<TProperty, int>(comparer);

    foreach (var item in source)
    {
        TProperty property = duplicateSelector(item);
        counts.TryGetValue(property, out int count);

        switch (count)
        {
            case 0:
                counts[property] = ++count;
                break;

            case 1:
                counts[property] = ++count;
                yield return property;
                break;
        }
    }
}

这里的技巧是在重复计数达到1后避免额外的查找成本。当然,如果您还想要每个项目的重复出现次数,您可以继续使用字典来更新计数。对于空值,您只需要进行一些额外的处理即可。

-3

通过键删除重复项

myTupleList = myTupleList.GroupBy(tuple => tuple.Item1).Select(group => group.First()).ToList();

问题不在于删除重复项。 - Gert Arnold

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接