提问人:Damkulul 提问时间:8/21/2023 最后编辑:Guru StronDamkulul 更新时间:8/22/2023 访问量:29
如何根据特定属性在列表中查找重复项
How to find duplicates in list according to specific attribute
问:
我有这个清单:List<manageMonthly> smsMngrDataMonthly = new List<manageMonthly>();
{"BILL","321"}{"RUTH","222"}{"DAVID","321"}{"ANNA","111"}
该类是:
public class manageMonthly
{
public string FullNameMonthly { get; set; }
public string AssetNumber { get; set; }
}
我需要根据资产编号获取所有重复的对象 - Bill 和 David,我尝试了我在网上找到的几个 linq 示例,但都不起作用(我得到了空值) 例如-
var duplicatesa = smsMngrDataMonthly.GroupBy(x => x.AssetNumber).Any(g => g.Count() > 1);
var duplicatesb = smsMngrDataMonthly.GroupBy(x => x.AssetNumber).Where(g => g.Count() > 1);
我错过了什么?
答:
0赞
Carlo Bos
8/22/2023
#1
你的代码似乎对我有用。也许问题在于您如何使用分组的结果?在执行此操作时,您可以显示每个重复的管理器。SelectMany
List<ManageMonthly> smsMngrDataMonthly = new List<ManageMonthly> {
new ManageMonthly {FullNameMonthly = "BILL", AssetNumber = "321"},
new ManageMonthly {FullNameMonthly = "RUTH", AssetNumber = "222"},
new ManageMonthly {FullNameMonthly = "DAVID",AssetNumber = "321"},
new ManageMonthly {FullNameMonthly = "ANNA", AssetNumber = "111"}};
var dups = smsMngrDataMonthly
.GroupBy(x => x.AssetNumber)
.Where(x => x.Count() > 1);
dups.SelectMany(d => d)
.ToList()
.ForEach(d => Console.WriteLine(d.FullNameMonthly));
这将返回:
BILL
DAVID
评论
Any
Where