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?
views:
115answers:
5
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
2010-01-29 14:37:17
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
2010-01-29 14:44:39
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
2010-01-29 14:45:30
+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
2010-01-29 14:49:19
You could improve performance by avoiding the intermediate `List<Order>`. The `HashSet<T>` constructor can take an `IEnumerable<T>` directly.
LukeH
2010-01-29 15:20:38
@Luke, yap thanks, I overcomplicating. Of course the ordersList will always have the same count as the original list.
herzmeister der welten
2010-01-29 15:37:34
@Jason, I think I originally saw some answers posted with some Count() statements nested. And Count() in Linq is definately evil.
herzmeister der welten
2010-01-29 15:38:53
+2
A:
bool hasDuplicates = myObjectList.Count >
new HashSet<int>(myObjectList.Select(x => x.Order)).Count;
LukeH
2010-01-29 15:19:16
+1
A:
What about Distinct
?
bool allUnique = ordersList.Count == ordersList.Select(o => o.Order).Distinct().Count()
Daren Thomas
2010-01-29 15:24:04