iTayb
iTayb

Reputation: 12743

How can I get a string[] of all different values of a list?

I have a class that has an list<Book> in it, and those Book objects has many many properties. string Subject is one of those properties.

I'd like to get an string[] type value that will include all different subjects from all over the list.

Is there an elegant way to do it, or I'll have to scan the whole list and enter each subject to it, then remove duplicates?

Upvotes: 3

Views: 125

Answers (2)

Guffa
Guffa

Reputation: 700372

This will return the distinct subjects:

books.Select(b => b.Subject).Distinct()

To create an array with the strings, use the ToArray method:

string[] subjects = books.Select(b => b.Subject).Distinct().ToArray();

Upvotes: 5

EgorBo
EgorBo

Reputation: 6142

 string[] subjects = books.Select(i => i.Subject).Distinct().ToArray();

Upvotes: 9

Related Questions