Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Tom Avatar asked Oct 14 '10 15:10

Tom


People also ask

Can we use LINQ query in a list object?

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.

What does SelectMany do in LINQ?

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.

How do you use select many?

SelectMany(<selector>) method For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example: int[][] arrays = { new[] {1, 2, 3}, new[] {4}, new[] {5, 6, 7, 8}, new[] {12, 14} }; // Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 } IEnumerable<int> result = arrays.


1 Answers

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(); 
like image 173
SLaks Avatar answered Sep 21 '22 13:09

SLaks