LINQ Getting Unique items from a List within a List

六月ゝ 毕业季﹏ 提交于 2019-12-23 07:50:55

问题


I have a List of type MyObject with a definition below:

class MyObject {
     public string ListName { get; set; }
     public IEnumerable<OtherObject> ObjectList { get; set;}
}

Given a List of type MyObject, using LINQ what expression should I use to get all distinct OtherObject?

What I was planning to do was loop each MyObject and get the distinct OtherObject from the ObjectList property, but then I need to get the distinct across the list.

Please note that if: MyObject[0].Objectlist[0] == 'ItemA' and MyObject[1].Objectlist[0] == 'ItemA' it will still return a single instance of ItemA. This code is just a representation only. This is not how I access my objects, by the way.


回答1:


You can achieve this simply using Set logic. C# has a nice implementation in the form of HashSet:

var set = new HashSet<OtherObject>(myObjects.SelectMany(mo => mo.ObjectList));

Or if you prefer deferred execution, you can use the LINQ Distinct method:

var distinct = myObjects.SelectMany(mo => mo.ObjectList).Distinct();



回答2:


How about:

var l = new List<MyObject>(...);
var unique = l.SelectMany(j => j.ObjectList).Distinct();

You can use the technique from Distinct() with lambda? to alter how you decide if an object is distinct from another.



来源:https://stackoverflow.com/questions/11447766/linq-getting-unique-items-from-a-list-within-a-list

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