C# 使用组选择重复项
Posted
技术标签:
【中文标题】C# 使用组选择重复项【英文标题】:C# select duplicate using group 【发布时间】:2021-10-27 05:20:36 【问题描述】:我只想从任何组多次包含相同 ID 的非空白名称中进行选择:
数据设置
var a1 = new id = 3, Name = "", Group = "GroupA" ;
var a2 = new id = 2, Name = "", Group = "GroupA" ;
var a3 = new id = 3, Name = "", Group = "GroupA" ;
var b1 = new id = 4, Name = "B", Group = "GroupB" ;
var b2 = new id = 5, Name = "B", Group = "GroupB" ;
var b3 = new id = 5, Name = "B", Group = "GroupB" ;
List<dynamic> group = new List<dynamic>();
group.Add(a1);
group.Add(a2);
group.Add(a3);
group.Add(b1);
group.Add(b2);
group.Add(b3);
查询:
var query1 = group.ToList()
.Where(s=>s.Name != "")
.GroupBy(x =>x.Group)
.Where(g => g.Count() > 1)
.SelectMany(y => y)
.ToList();
Console.WriteLine("output\n" + string.Join("\n", query1));
返回
id = 4, Name = B, Group = GroupB
id = 5, Name = B, Group = GroupB
id = 5, Name = B, Group = GroupB
但我想要的是以下内容:
id = 5, Name = B, Group = GroupB
id = 5, Name = B, Group = GroupB
我做错了什么?
【问题讨论】:
具有相同id
但不同Group
的项目会发生什么情况?例如。 new id=1,Group="A"
和 new id=1,Group="B"
.
【参考方案1】:
根据您的需要按id
和/或Name
分组
.GroupBy(x => new x.id, x.Name)
给定
var list = new[]
new id = 3, Name = "", Group = "GroupA",
new id = 2, Name = "", Group = "GroupA",
new id = 3, Name = "", Group = "GroupA",
new id = 4, Name = "B", Group = "GroupB",
new id = 5, Name = "B", Group = "GroupB",
new id = 5, Name = "B", Group = "GroupB"
;
用法
var results = list
.Where(s => s.Name != "")
.GroupBy(x => new x.id, x.Name)
// .GroupBy(x => x.id) <- depending on your needs
.Where(g => g.Count() > 1)
.SelectMany(y => y);
foreach (var result in results)
Console.WriteLine($"result.id, result.Name, result.Group");
输出
5, B, GroupB
5, B, GroupB
【讨论】:
谢谢,如果我把名字改成 A B C,我怎样才能得到同样的结果?【参考方案2】:您正在将GroupBy
应用于Group
属性。不要按Group
属性分组,而是使用id
属性,
输入
var list = new[]
new id = 3, Name = "", Group = "GroupA",
new id = 2, Name = "", Group = "GroupA",
new id = 3, Name = "", Group = "GroupA",
new id = 4, Name = "B", Group = "GroupB",
new id = 5, Name = "B", Group = "GroupB",
new id = 5, Name = "B", Group = "GroupB"
;
解决方案:
var query1 = list.ToList()
.Where(s=>s.Name != "")
.GroupBy(x =>x.id)
//^^^^^ This change you need to do
.Where(g => g.Count() > 1)
.SelectMany(y => y)
.ToList();
输出
5, B, GroupB
5, B, GroupB
Try it online
【讨论】:
以上是关于C# 使用组选择重复项的主要内容,如果未能解决你的问题,请参考以下文章