DonCarnage
DonCarnage

Reputation: 31

Determine whether two or more objects in a list are equal according to some property

Say I have a list List<MyObject> myObjectList. The MyObject object has a property named Order which is of type int. How can I determine whether two or more objects in myObjectList have the same Order using LINQ-to-objects?

Upvotes: 3

Views: 516

Answers (5)

Daren Thomas
Daren Thomas

Reputation: 70344

What about Distinct?

bool allUnique = ordersList.Count == ordersList.Select(o => o.Order).Distinct().Count()

Upvotes: 1

LukeH
LukeH

Reputation: 269628

bool hasDuplicates = myObjectList.Count >
    new HashSet<int>(myObjectList.Select(x => x.Order)).Count;

Upvotes: 2

herzmeister
herzmeister

Reputation: 11297

Not a pure Linq-To-Objects-Solution, but how about:

var ordersList = new List<Order>(myObjectList.Select(obj => obj.Order);
bool allUnique = ordersList.Count == new HashSet<Order>(ordersList).Count;

One would have to test performance of all the approaches presented here. I'd be careful, otherwise you end up quickly with some slow O(n²) look-ups.

Upvotes: 1

jason
jason

Reputation: 241779

First GroupBy MyObject.Order and then determine if Any of the groups have more than one member:

bool b = myObjectList.GroupBy(x => x.Order)
                     .Any(g => g.Count() > 1);
// b is true is there are at least two objects with the same Order
// b is false otherwise

Upvotes: 11

Agent_9191
Agent_9191

Reputation: 7253

The Count() method takes a predicate, so you would do something like this:

if(myObjectList.Count(x => x.Order == 1) >= 2)
{
    // Do something
}

Upvotes: -1

Related Questions