1

I have a generic list of assets (List<Asset>) and one of the assets properties is called Tags which is a list of strings

How would I do a Linq query to get a distinct list of tags. I tried

assetList.Select(a => a.Tags).Distinct() 

but this returns me an IEnumerable<List<string>> instead of an IEnumerable<string>

3 Answers3

1

You was close. You need to use Enumerable.SelectMany to select all tags and flatten them into one sequence:

assetList.SelectMany(a => a.Tags).Distinct() 
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0
assetList.SelecMany(a => a.Tags).Distinct() . correct it

more information about differences Difference Between Select and SelectMany

Community
  • 1
  • 1
Eugene P.
  • 2,645
  • 19
  • 23
0

Select only takes objects as they are and Tags is a list, so it takes lists. If you need items from these lists, you have to flatten them into one list and then proceed with other operations.

assetList.SelectMany(a => a.Tags).Distinct();

A nice example from MSDN on SelectMany

PetOwner[] petOwners = 
                { new PetOwner { Name="Higa, Sidney", 
                      Pets = new List<string>{ "Scruffy", "Sam" } },
                  new PetOwner { Name="Ashkenazi, Ronen", 
                      Pets = new List<string>{ "Walker", "Sugar" } },
                  new PetOwner { Name="Price, Vernette", 
                      Pets = new List<string>{ "Scratches", "Diesel" } } };

IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);

produces the following list

Scruffy, Sam, Walker, Sugar, Scratches, Diesel

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93