Let\'s say we have a List
and each product item in the list has many List
public class Product{
public int
The following does what you want:
var productsPerType =
from t in products.SelectMany(
p => p.Types, (p, t) => new { Product = p, TypeId = t.Id })
group t by t.TypeId
into g
select new { g.Key, Products = g.Select(x => x.Product) };
First, you do a SelectMany
to get a list of all types inside the products. For each type you remember the type id and the corresponding product:
from t in products.SelectMany(
p => p.Types, (p, t) => new { Product = p, TypeId = t.Id })
Each t
is now an anonymous object containing a type id and a product. Next, you group these objects by type id. Now we have a group of products for each type id.
To give you an example, suppose you have the following products and types:
Product A -- Types 1, 2, 3
Product B -- Types 1
Product C -- Types 1, 3
The SelectMany
gives the following intermediate result:
1, A
2, A
3, A
1, B
1, C
3, C
We group this result by type id so we get the following groups:
1, { A, B, C }
2, { A }
3, { A, C }
And this is the result you wanted.