Jon Galloway
Jon Galloway

Reputation: 53115

LINQ - Select all children from an object hierarchy

I have a List of objects which contain a string array as one of their properties. I want to get a distinct string array containing all the values.

My object looks like this:

public class Zoo {
    string Name { get; set;}
    string[] Animals { get; set;}
}

Some zoos may have only one animal, some may have many. What would be the simplest Lambda expression or LINQ query to get me a unique list of all animals at all the Zoos in List<Zoo>?

Upvotes: 6

Views: 13105

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499810

var query = zoos.SelectMany(zoo => zoo.Animals)
                .Distinct();

Or if you're a query expression fan (I wouldn't be for something this simple):

var query = (from zoo in zoos
             from animal in zoo.Animals
             select animal).Distinct();

Upvotes: 18

Related Questions