If you have a list of products and each product has a list of categories.
How do I get the list of cateories used by the products?
List<Product> products = new List<Product>();
Product product1 = new Product();
product1.Categories.Add("Books");
product1.Categories.Add("Electronics");
Product product2 = new Product();
product2.Categories.Add("Dishes");
product2.Categories.Add("Books");
products.Add( product1 );
products.Add( product2 );
How Do I get a list "Books", "Dishes", "Electronics"
You can use SelectMany
var result = products.SelectMany(x => x.Categories).Distinct().ToList();
This is what SelectMany does and I quote MSDN.
Projects each element of a sequence to an IEnumerable(Of T) and flattens the resulting sequences into one sequence.
Here is a working proof.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With