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

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

问题描述

我有一个 List 像:

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

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

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.

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

是否有任何想法可以使用 LINQlambda 表达式?

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

推荐答案

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

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

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天全站免登陆