LINQ - select all children from the object hierarchy

I have Listobjects that contain an array of strings as one of their properties. I want to get a separate string array containing all the values.

My object is as follows:

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

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

+5
source share
1 answer
var query = zoos.SelectMany(zoo => zoo.Animals)
                .Distinct();

Or, if you are a fan of query expressions (I would not be so simple):

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

All Articles