2014-10-29 108 views
1

Hej,我有linq表達的問題。我想與一些組合進行加入。這基本上是我需要的: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連接子句中的一個表達式的類型不正確。在「加入」的調用中,類型推斷失敗。

如何正確編寫此表達式?

+1

您正在尋找的是GroupJoin。考慮這[後](http://stackoverflow.com/a/15599143/1039635) – 2014-10-29 08:19:39

+0

嗨,如果你發現答案有幫助也許接受它作爲答案? – 2014-10-30 10:43:06

回答

2

我已經包含了一些示例代碼,它正在做你正在做的事情。它從一些示例代碼改編來使用兩個類而不是靜態字符串數組。

結果將生成帶有ProductCategory字段的IEnumerable,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() }; 
+0

你的答案和Iurii Khrystiuk是有用的,我注意到我只是用不正確的順序做出錯誤的查詢。 – Puchacz 2014-10-29 19:41:58