如何使用LINQ从列表中获取重复项?

问题描述 投票:164回答:9

我有一个像List<string>

List<String> list = new List<String>{"6","1","2","4","6","5","1"};

我需要将列表中的重复项目放入新列表中。现在我使用嵌套的for循环来做到这一点。

由此产生的list将包含{"6","1"}

有没有想过使用LINQlambda expressions这样做?

c# linq duplicates
9个回答
231
投票
var duplicates = lst.GroupBy(s => s)
    .SelectMany(grp => grp.Skip(1));

请注意,这将返回所有重复项,因此,如果您只想知道源列表中哪些项重复,则可以将Distinct应用于生成的序列或使用Mark Byers给出的解决方案。


169
投票

这是一种方法:

List<String> duplicates = lst.GroupBy(x => x)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();

GroupBy将相同的元素组合在一起,而Where会筛选出只出现过一次的元素,只留下重复的元素。


37
投票

这是另一种选择:

var list = new List<string> { "6", "1", "2", "4", "6", "5", "1" };

var set = new HashSet<string>();
var duplicates = list.Where(x => !set.Add(x));

22
投票

我知道这不是原始问题的答案,但你可能会发现自己遇到了这个问题。

如果您想要结果中的所有重复项,则以下方法有效。

var duplicates = list
    .GroupBy( x => x )               // group matching items
    .Where( g => g.Skip(1).Any() )   // where the group contains more than one item
    .SelectMany( g => g );           // re-expand the groups with more than one item

在我的情况下,我需要所有重复项,以便我可以在UI中将它们标记为错误。


18
投票

我根据@ Lee对OP的回应编写了这个扩展方法。注意,使用了默认参数(需要C#4.0)。但是,在C#3.0中重载方法调用就足够了。

/// <summary>
/// Method that returns all the duplicates (distinct) in the collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <param name="source">The source collection to detect for duplicates</param>
/// <param name="distinct">Specify <b>true</b> to only return distinct elements.</param>
/// <returns>A distinct list of duplicates found in the source collection.</returns>
/// <remarks>This is an extension method to IEnumerable&lt;T&gt;</remarks>
public static IEnumerable<T> Duplicates<T>
         (this IEnumerable<T> source, bool distinct = true)
{
     if (source == null)
     {
        throw new ArgumentNullException("source");
     }

     // select the elements that are repeated
     IEnumerable<T> result = source.GroupBy(a => a).SelectMany(a => a.Skip(1));

     // distinct?
     if (distinct == true)
     {
        // deferred execution helps us here
        result = result.Distinct();
     }

     return result;
}

10
投票

希望这会有所帮助

int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };

var duplicates = listOfItems 
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key);

foreach (var d in duplicates)
    Console.WriteLine(d);

10
投票
  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };

    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }

2
投票

我试图用一个对象列表来解决这个问题并且遇到了问题,因为我试图将组列表重新打包到原始列表中。所以我想出了循环遍历组以使用具有重复项的项重新打包原始列表。

public List<MediaFileInfo> GetDuplicatePictures()
{
    List<MediaFileInfo> dupes = new List<MediaFileInfo>();
    var grpDupes = from f in _fileRepo
                   group f by f.Length into grps
                   where grps.Count() >1
                   select grps;
    foreach (var item in grpDupes)
    {
        foreach (var thing in item)
        {
            dupes.Add(thing);
        }
    }
    return dupes;
}

0
投票

所有提到的解决方案直到现在才执行GroupBy。即使我只需要第一个Duplicate,集合中的所有元素都至少枚举一次。

一旦找到重复项,以下扩展功能就会停止枚举。如果请求下一个副本,它将继续。

和LINQ一样,有两个版本,一个是IEqualityComparer,一个是没有它。

public static IEnumerable<TSource> ExtractDuplicates(this IEnumerable<TSource> source)
{
    return source.ExtractDuplicates(null);
}
public static IEnumerable<TSource> ExtractDuplicates(this IEnumerable<TSource source,
    IEqualityComparer<TSource> comparer);
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (comparer == null)
        comparer = EqualityCompare<TSource>.Default;

    HashSet<TSource> foundElements = new HashSet<TSource>(comparer);
    foreach (TSource sourceItem in source)
    {
        if (!foundElements.Contains(sourceItem))
        {   // we've not seen this sourceItem before. Add to the foundElements
            foundElements.Add(sourceItem);
        }
        else
        {   // we've seen this item before. It is a duplicate!
            yield return sourceItem;
        }
    }
}

用法:

IEnumerable<MyClass> myObjects = ...

// check if has duplicates:
bool hasDuplicates = myObjects.ExtractDuplicates().Any();

// or find the first three duplicates:
IEnumerable<MyClass> first3Duplicates = myObjects.ExtractDuplicates().Take(3)

// or find the first 5 duplicates that have a Name = "MyName"
IEnumerable<MyClass> myNameDuplicates = myObjects.ExtractDuplicates()
    .Where(duplicate => duplicate.Name == "MyName")
    .Take(5);

对于所有这些linq语句,只会解析集合,直到找到所请求的项目。序列的其余部分未被解释。

恕我直言,这是一个提高效率的考虑因素。

© www.soinside.com 2019 - 2024. All rights reserved.