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?
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?
this is how i would do it without the need to do group-by in one line:
For what it's worth, I just compared the two methods we've struck upon in this thread. First I defined a helper class:
... and then made a big list of instances with a random ID:
... and lastly, timed the code:
Here's one output:
So I think it's safe to say that grouping and then comparing the count of groups to the count of items is way, way faster than doing a brute-force "nested Any" comparison.
My take (no counting!):
That's a bit of a brute-force approach but it works. There might be a smarter way to do it using the Except() extension method.
Edit: You didn't actually say that you needed to know which items are "duplicated", only that you needed to know whether any where. This'll do the same thing except give you a list you can iterate over:
list.Where(i => list.Any(j => j.ID == i.ID && j != i))
I like the grouping approach too (group by ID and find the groups with count > 1).
Similar to Y Low's approach,
Edited: