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
For what it's worth, I just compared the two methods we've struck upon in this thread. First I defined a helper class:
public class Foo
{
public int ID;
}
... and then made a big list of instances with a random ID:
var list = new List();
var r = new Random();
for (int i = 0; i < 10000; i++) list.Add(new Foo { ID = r.Next() });
... and lastly, timed the code:
var sw = new Stopwatch();
sw.Start();
bool b = list.Any(i => list.Where(j => i != j).Any(j => j.ID == i.ID));
Console.WriteLine(b);
Console.WriteLine(sw.ElapsedTicks);
sw.Reset();
sw.Start();
b = (list.GroupBy(i => i.ID).Count() != list.Count);
Console.WriteLine(b);
Console.WriteLine(sw.ElapsedTicks);
Here's one output:
False
59392129
False
168151
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.