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

我有一个List<string>像:

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

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

结果list将包含{"6","1"}

有没有任何想法使用LINQ或lambdaexpression式来做到这一点?

 var duplicates = lst.GroupBy(s => s) .SelectMany(grp => grp.Skip(1)); 

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

这是一个办法:

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

GroupBy将相同的元素分组在一起,而Where过滤掉那些只出现一次的元素,只留下重复的元素。

这是另一个select:

 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)); 

我知道这不是原来问题的答案,但是你可能会遇到这个问题。

如果你想要结果中的所有重复项目,下面的工作。

 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中标记为错误。

我写了这个扩展方法,基于@李对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; } 
  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); } 

希望这会有所帮助

 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); 

我试图解决与对象列表相同,并有问题,因为我试图重新组到原始列表中的列表。 所以我想出了通过组循环来重新包装与重复项目的原始列表。

 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; }