linq加入团体

时间:2014-10-29 08:07:27

标签: c# linq

Hej,我对linq表达式有疑问。我想与某些小组进行联接。这基本上就是我需要的:

var f = new IEnumerable<SomeClass> { ... };
var rows = new IEnumerable<SomeOtherClass> { ... };
var makedGroups = rows.GroupBy(row => row.SomeId);
var groupsJoined = (from row in makedGroups
    join allocQuant in f on row.Key.Value equals allocQuant.SomeId into gj
    select gr => new { Count = gr.Count(), Group = gj });

错误是:错误202 join子句中某个表达式的类型不正确。调用“加入”时类型推断失败。

如何正确编写此表达式?

1 个答案:

答案 0 :(得分:2)

我已经包含了一些示例代码,这些代码正在执行您要执行的操作。它改编自一些示例代码,使用两个类而不是静态字符串数组。

结果将产生IEnumerable使用ProductCategory字段,Products字段包含基于类别的产品分组,最后一列是分组中的计数。

根据你的要求,这就是我认为你想要的。

class Product
{

    public Product(string cat, string name)
    {
        Category = cat;
        ProductName = name;
    }

    public string Category { get; set;}
    public string ProductName { get;set;}
}


class ProductClass
{
    public ProductClass (string type)
    {
        ProductType = type;
    }   

    public string ProductType { get;set;}
}

ProductClass[] productClasses = new ProductClass[]{  
    new ProductClass("Beverages"),   
    new ProductClass("Condiments"),   
    new ProductClass("Vegetables"),   
    new ProductClass("Dairy Products"),   
    new ProductClass("Seafood") };  

List<Product> products = new List<Product>();
products.Add(new Product("Seafood", "crab sticks"));
products.Add(new Product("Seafood", "lobster"));
products.Add(new Product("Vegetables", "cucumber"));
products.Add(new Product("Seafood", "oysters"));
products.Add(new Product("Condiments", "pepper"));
products.Add(new Product("Condiments", "salt"));

var query =
    from pc in productClasses
    join product in products on pc.ProductType equals product.Category into gj
    select new { ProductCategory= pc.ProductType, Products = gj, Count = gj.Count() };