LINQy way to check if any objects in a collection have the same property value

后端 未结 6 584
庸人自扰
庸人自扰 2020-12-17 00:07

I have a class Agent with a property Id

Given a collection of Agents I need to check if any of them have duplicate Ids.

I am currently doing this with a hash

6条回答
  •  猫巷女王i
    2020-12-17 00:25

    Similar to Y Low's approach,

    Edited:

     var duplicates = agents.GroupBy(a => a.ID).Where(a=>a.Count() > 1);
    
     foreach (var agent in duplicates)
     {
             Console.WriteLine(agent.Key.ToString());
     }
    

提交回复
热议问题