如何根据特定属性在列表中查找重复项

How to find duplicates in list according to specific attribute

提问人:Damkulul 提问时间:8/21/2023 最后编辑:Guru StronDamkulul 更新时间:8/22/2023 访问量:29

问:

我有这个清单: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);

我错过了什么?

列出 LINQ 重复项

评论

0赞 Guru Stron 8/21/2023
“(I got nulls)” - 你到底从哪里得到空值?
0赞 Guru Stron 8/21/2023
你能提供一个最小的可重复的例子吗?
0赞 Damkulul 8/22/2023
@GuruStron vars : duplicatesa 和 duplicatesb 为 null。
1赞 Jon Skeet 8/22/2023
这些变量永远不会为 null。of 的结果是一个布尔值,而 of 的结果从不为 null - 但它可能是一个空序列。请提供一个最小的可重复示例AnyWhere

答:

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