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

前端 未结 2 1740
北恋
北恋 2020-12-24 01:00
public class ClassA
{
     public string MyString {get; set;}
}

public class ClassB
{
     public List MyObjects {get; set;}
}

List cla         


        
相关标签:
2条回答
  • 2020-12-24 01:20

    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();
    
    0 讨论(0)
  • 2020-12-24 01:43

    You want to use IEnumerable.SelectMany() Extension Method to flatten the hierarchy:

    var result = classBList.SelectMany(b => b.MyObjects).Distinct();
    
    0 讨论(0)
提交回复
热议问题