C#从List <Item>中查找所有匹配的项目

ran*_*ika 9 c# linq

假设我们有一个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;}
}
Run Code Online (Sandbox Code Playgroud)

在创建产品列表后,我需要按类型对它们进行分组,然后找到属于每种类型的所有内容.我想我应该尝试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);
                                }
                            }
Run Code Online (Sandbox Code Playgroud)

然后我试着像这样搜索

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
}
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*erg 8

以下是您想要的:

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) };
Run Code Online (Sandbox Code Playgroud)

首先,您SelectMany可以获取产品内所有类型的列表.对于每种类型,您都记得类型ID和相应的产品:

from t in products.SelectMany(
    p => p.Types, (p, t) => new { Product = p, TypeId = t.Id })
Run Code Online (Sandbox Code Playgroud)

t现在每个都是一个包含类型ID和产品的匿名对象.接下来,按类型id对这些对象进行分组.现在我们为每种类型的id提供了一组产品.

举个例子,假设您有以下产品和类型:

Product A -- Types 1, 2, 3
Product B -- Types 1
Product C -- Types 1, 3
Run Code Online (Sandbox Code Playgroud)

SelectMany给出以下中间结果:

1, A
2, A
3, A
1, B
1, C
3, C
Run Code Online (Sandbox Code Playgroud)

我们按类型ID对此结果进行分组,因此我们得到以下组:

1, { A, B, C }
2, { A }
3, { A, C }
Run Code Online (Sandbox Code Playgroud)

这就是你想要的结果.