Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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"

like image 227
Mathias F Avatar asked Dec 09 '22 12:12

Mathias F


1 Answers

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

like image 98
Nikhil Agrawal Avatar answered Dec 11 '22 06:12

Nikhil Agrawal