Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Select all children from an object hierarchy

Tags:

c#

linq

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>?

like image 696
Jon Galloway Avatar asked Aug 04 '09 20:08

Jon Galloway


1 Answers

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();
like image 153
Jon Skeet Avatar answered Nov 02 '22 07:11

Jon Skeet