views:

115

answers:

5

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?

A: 

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

if(myObjectList.Count(x => x.Order == 1) >= 2)
{
    // Do something
}
Agent_9191
That only checks if there is a duplicate with `MyObject.Order` equal to `1`. It ignores the possibility of there being a duplicate with `MyObject.Order` equal to any other `int`.
Jason
This would only test whether there are multiple objects with Order==1, not if there are two objects with the same (unknown) value.
Hans Kesting
+10  A: 

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
Jason
+1  A: 

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.

herzmeister der welten
You could improve performance by avoiding the intermediate `List<Order>`. The `HashSet<T>` constructor can take an `IEnumerable<T>` directly.
LukeH
What has `O(n^2)` lookups?
Jason
@Luke, yap thanks, I overcomplicating. Of course the ordersList will always have the same count as the original list.
herzmeister der welten
@Jason, I think I originally saw some answers posted with some Count() statements nested. And Count() in Linq is definately evil.
herzmeister der welten
+2  A: 
bool hasDuplicates = myObjectList.Count >
    new HashSet<int>(myObjectList.Select(x => x.Order)).Count;
LukeH
+1  A: 

What about Distinct?

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