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

好久不见. 提交于 2020-01-04 02:54:06

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


What about Distinct?

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



回答5:


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

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


来源:https://stackoverflow.com/questions/2162545/determine-whether-two-or-more-objects-in-a-list-are-equal-according-to-some-prop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!