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

后端 未结 6 582
庸人自扰
庸人自扰 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条回答
  •  盖世英雄少女心
    2020-12-17 00:23

    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.

提交回复
热议问题