How to get a list of all subobjects contained in the list of objects?

If you have a list of products and each product has a list of categories.

How to get a list of directories used by 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 to get a list of "Books", "Tableware", "Electronics"

+4
source share
1 answer

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.

enter image description here

+13
source

All Articles