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

I have a class with list<Book>in it, and those Bookobjects have many properties. string Subjectis one of those properties.

I would like to get a type value string[]that will include all the different items from the list.

Is there an elegant way to do this, or will I have to scan the entire list and enter every object into it, and then delete duplicates?

+3
source share
2 answers

This will return individual topics:

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

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

string[] subjects = books.Select(b => b.Subject).Distinct().ToArray();
+5
source
 string[] subjects = books.Select(i => i.Subject).Distinct().ToArray();
+9
source

Source: https://habr.com/ru/post/1738478/


All Articles