如何从使用LINQ列表中的重复项目? [英] How to get duplicate items from a list using LINQ?

查看:131
本文介绍了如何从使用LINQ列表中的重复项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表与LT;串> 这样的:

 列表<串GT;列表=新列表与所述;字符串> {6,1,2,4,6,5,1};

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

生成的列表将包含 {6,1}

有任何想法要做到这一点使用 LINQ 或的拉姆达前pressions 的?


解决方案

  VAR重复= lst.GroupBy(S = GT S)
    .SelectMany(GRP = GT; grp.Skip(1));

请注意,这将返回所有重复,所以如果你只是想知道哪些项目源列表中是重复的,可以申请鲜明来生成的序列或使用由Mark Byers公司给出的解决方案。

I'm having a List<string> like:

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

I need to get the duplicate items in the list into a new list. Now I'm using a nested for loop to do this.

The resulting list will contain {"6","1"}.

Is there any idea to do this using LINQ or lambda expressions?

解决方案

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

Note that this will return all duplicates, so if you only want to know which items are duplicated in the source list, you could apply Distinct to the resulting sequence or use the solution given by Mark Byers.

这篇关于如何从使用LINQ列表中的重复项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆