我已經包含了一些示例代碼,它正在做你正在做的事情。它從一些示例代碼改編來使用兩個類而不是靜態字符串數組。
結果將生成帶有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() };
您正在尋找的是GroupJoin。考慮這[後](http://stackoverflow.com/a/15599143/1039635) – 2014-10-29 08:19:39
嗨,如果你發現答案有幫助也許接受它作爲答案? – 2014-10-30 10:43:06