Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();

Try this:

var distinctFooBars = (from foo in foos
                       select foo.Bar).Distinct().ToArray();

Shouldn't you be able to do something like:

var strings = (from a in fooList select a.Bar).Distinct();
string[] array = strings.ToArray();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top