tags:

views:

708

answers:

4

I have a List of Foo. Foo has a string property named Bar. I'd like to use linq to get a string[] of distinct values for Foo.Bar in List of Foo.

How can I do this?

+1  A: 

Try this:

var distinctFooBars = (from foo in foos
                       select foo.Bar).Distinct().ToArray();
Lasse V. Karlsen
+3  A: 

This should work if you want to use the fluent pattern:

string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();
Guy
+3  A: 

I'd go lambdas... wayyy nicer

var bars = Foos.Select(f => f.Bar).Distinct().ToArray();

works the same as what @lassevk posted.

I'd also add that you might want to keep from converting to an array until the last minute.

LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether.

By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc.

chakrit
A: 

Shouldn't you be able to do something like this?

var strings = (from a in fooList select a.Bar).Distinct(); string[] array = strings.ToArray();