LINQ获取独特的项目从列表中列表中 [英] LINQ Getting Unique items from a List within a List

查看:149
本文介绍了LINQ获取独特的项目从列表中列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表键入为MyObject 下面定义的:

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

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



给定一个列表类型为MyObject ,使用LINQ是什么表情,我应该用它来获取所有不同的 OtherObject

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

我正打算做的是循环的每个为MyObject ,并获得不同的 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.

请注意,如果:
为MyObject [0] .Objectlist [0] ==意达为MyObject [1] .Objectlist [0] ==意达它仍然会返回意达的一个实例。这个代码仅只是一种表象。这不是我如何访问我的对象,顺便说一句。

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.

推荐答案

可以做到这一点只需使用的设置逻辑。 C#在 HashSet的:

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));



或者,如果你愿意延迟执行,你可以使用LINQ的Distinct 方式:

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

这篇关于LINQ获取独特的项目从列表中列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆