Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of distinct property values from in memory lists?

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?

like image 703
Dane O'Connor Avatar asked Dec 30 '22 11:12

Dane O'Connor


1 Answers

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.

like image 157
chakrit Avatar answered Jan 27 '23 18:01

chakrit