简体   繁体   中英

Using LINQ, select list of objects inside another list of objects

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

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.

You're trying to select multiple result objects for each ClassB object in the original list.

Therefore, you're looking for the SelectMany extension method :

var results = classBList.SelectMany(b => b.MyObjects).Distinct();

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

您希望使用IEnumerable.SelectMany()扩展方法来展平层次结构:

var result = classBList.SelectMany(b => b.MyObjects).Distinct();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM