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 Answers 3

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() 
Sign up to request clarification or add additional context in comments.

Comments

0
assetList.SelecMany(a => a.Tags).Distinct() . correct it

more information about differences Difference Between Select and SelectMany

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.