Let's say we have a List<Product> and each product item in the list has many List<Type>
public class Product{
public int Id {get:set;}
public string Name {get:set;}
public List<Type> Types {get;set;}
}
public class Type{
public int Id {get;set;}
public string Name{get;set;}
}
After I create a product list, I need to group them by the type and then find all the belongs to each type. I think I should try LINQ for this. Here is what I have done so far, but seems not the right way to get the job done. May be someone can help me.
var productsList = new List<Product>();
//Adding products and types for each of them
var productTypesList = new Dictionary<int, string>();
foreach (var p in productsList)
{
var pTypes = p.Types;
foreach (var ptype in
pTypes.Where(x=> !productTypesList .ContainsKey(x.Id)))
{
productTypesList.Add(ptype.Id, ptype.Name);
}
}
Then I'm trying to search Like this
foreach (var t in productTypesList)
{
var matches = productsList.FindAll(........);
// from here I need to find all the product which belongs to type (t.id)
if (matches.Count > 0)
{
//Do somthing here
}
}