使用 LINQ,选择另一个对象列表中的对象列表 [英] Using LINQ, select list of objects inside another list of objects
本文介绍了使用 LINQ,选择另一个对象列表中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class ClassA
{
public string MyString {get; set;}
}
public class ClassB
{
public List<ClassA> MyObjects {get; set;}
}
List<ClassB> classBList = new List<ClassB>();
var results = (from i in classBList select i.MyObjects).Distinct();
我想要classBList
中所有ClassA
对象的不同列表.我如何使用 LINQ 解决这个问题?我正在考虑嵌套查询,但无法完全弄清楚.非常感谢任何帮助.
I want a distinct list of all the ClassA
objects in the classBList
. How do I go about this using LINQ? I'm thinking about a nested query, but couldn't quite figure it out. Any help is very appreciated.
推荐答案
您正试图为原始列表中的每个 ClassB
对象选择多个结果对象.
You're trying to select multiple result objects for each ClassB
object in the original list.
因此,您正在寻找 SelectMany
扩展方法:
Therefore, you're looking for the SelectMany
extension method:
var results = classBList.SelectMany(b => b.MyObjects).Distinct();
如果要使用查询表达式,则需要使用 两个 from
子句:
If you want to use query expressions, you'll need to use two from
clauses:
var results = (from b in classBList from a in b.MyObjects select a).Distinct();
这篇关于使用 LINQ,选择另一个对象列表中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文