56
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.

Tatranskymedved
  • 4,194
  • 3
  • 21
  • 47
Tom
  • 1,270
  • 2
  • 12
  • 25

2 Answers2

116

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();
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Does the query syntax you provide use SelectMany once translated? I'm a tad naive when it comes to query syntax since it always looks more verbose (except in join situations). – Justin Niessner Oct 14 '10 at 15:09
  • @Justin: Yes; those two expressions should compile identically. – SLaks Oct 14 '10 at 15:40
18

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

var result = classBList.SelectMany(b => b.MyObjects).Distinct();
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536