Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 table but am trying to get Linq-ified, what's a good way of doing this?

like image 422
George Mauer Avatar asked Nov 23 '08 02:11

George Mauer


1 Answers

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());
 }
like image 90
Codewerks Avatar answered Sep 24 '22 15:09

Codewerks