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

后端 未结 6 579
庸人自扰
庸人自扰 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:49

    bool b = list.Any(i => list.Any(j => j.ID == i.ID && j != i));
    

    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).

提交回复
热议问题