假设我们有一个
然后我尝试像这样搜索。
List<Product>
,列表中的每个产品条目都有许多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;}
}
在创建产品列表之后,我需要按类型对它们进行分组,然后找到属于每种类型的所有产品。我认为我应该尝试使用 LINQ
来完成这个任务。目前为止,我已经完成了以下工作,但似乎不是正确的方法来完成工作。也许有人可以帮助我。
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);
}
}
然后我尝试像这样搜索。
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
}
}