C# 如何在列表<>中查找重复项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15866780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find duplicate items in list<>?
提问by Monopompom
I have:
我有:
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };
How can I get only "a","b"?
我怎样才能只得到“a”、“b”?
I tried to do like this:
我试着这样做:
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };
List<string> test_list = new List<string>();
test_list = list.Distinct().ToList();
Now test_list has {"a", "b", "r", "t"}
And then:
现在 test_list 有 {"a", "b", "r", "t"}
然后:
test_list = test_list.Except(list).ToList();
So that was my fail point, cause Except() deleted all elements.
所以这是我的失败点,因为Except() 删除了所有元素。
Could you help me with solution?
你能帮我解决吗?
采纳答案by Sachin
Try this
尝试这个
var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();
回答by Sergei G
var duplicates = list.GroupBy(s => s).SelectMany(g => g.Skip(1).Take(1)).ToList();
回答by Tim Schmelter
A simple approach is using Enumerable.GroupBy
:
一个简单的方法是使用Enumerable.GroupBy
:
var dups = list.GroupBy(s => s)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
回答by I4V
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };
var dups = list.GroupBy(x => x)
.Where(x => x.Count() > 1)
.Select(x => x.Key)
.ToList();
回答by MarcinJuraszek
var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();
It will be more efficient then the one using Where(g => g.Count() > 1)
and will return only one element from every group.
它将比使用的更有效率,Where(g => g.Count() > 1)
并且只会从每个组中返回一个元素。
回答by dtb
var list = new List<string> { "a", "a", "b", "b", "r", "t" };
var distinct = new HashSet<string>();
var duplicates = new HashSet<string>();
foreach (var s in list)
if (!distinct.Add(s))
duplicates.Add(s);
// distinct == { "a", "b", "r", "t" }
// duplicates == { "a", "b" }