tags:

views:

269

answers:

1

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

+3  A: 
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();
Jon Skeet
Thanks, Jon. Typo on my part.
Jon Galloway
Where was the typo? I must have missed it :)
Jon Skeet
The typo was in my application. I can't wait until the StackOverflow addin for Visual Studio comes out so you can fix my apps as I work. :-)
Jon Galloway