【发布时间】:2015-03-03 17:17:37
【问题描述】:
我想按 categoryId 显示列表产品的名称组,这是我的代码:
我想查看我的显示结果:
Desktop
|_ PC HP - Red
|_ PC Dell - Yellow
|_ PC Asus - Red
SmartPhone
|_ Lumia 720 - Blue
我的 GroupModel:
public class GroupModel
{
public Category Categories { get; set; }
public Product Products { get; set; }
}
我的控制器:
List<Category> listCategories = new List<Category>
{
new Category {Id = 1, CateName = "SmartPhone"},
new Category {Id = 2, CateName = "Laptop"},
new Category {Id = 3, CateName = "Desktop"},
};
List<Product> listProducts = new List<Product>
{
new Product {Id = 1, ProdName = "Lumia 720", CategoryId = 1, ColorId = 2},
new Product {Id = 2, ProdName = "PC HP", CategoryId = 3, ColorId = 1},
new Product {Id = 3, ProdName = "PC Dell", CategoryId = 3, ColorId = 1},
new Product {Id = 4, ProdName = "Laptop Lenovo", CategoryId = 2, ColorId = 2},
new Product {Id = 5, ProdName = "Lumia 920", CategoryId = 1, ColorId = 2},
new Product {Id = 6, ProdName = "Laptop Dell", CategoryId = 2, ColorId = 3},
new Product {Id = 7, ProdName = "Laptop HP", CategoryId = 2, ColorId = 3}
};
List<Color> listColor = new List<Color>
{
new Color {ColorId = 1, ColorName = "Blue"},
new Color {ColorId = 2, ColorName = "Yellow"},
new Color {ColorId = 3, ColorName = "Red"}
};
var query = from c in listCategories
join p in listProducts on c.Id equals p.CategoryId
select new GroupModel
{
Categories = c,
Products = p
};
return View(query.ToList());
这是我绑定列表的观点。我正在使用 GroupModel 来嵌套 ProductModel 和 CategoryModel
@model IEnumerable<Test.Models.GroupModel>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(model => item.Categories.CateName)
</td>
</tr>
<tr>
<td>
@Html.Label("|__ ") @Html.DisplayFor(model => item.Products.ProdName)
</td>
</tr>
}
【问题讨论】:
-
你的输出应该是什么样子?
-
listProducts.GroupBy(x => x.CategoryId, x => x.ProdName). -
@Enigmativity:msdn.microsoft.com/en-us/library/… 是指哪个重载?
-
@abatishchev -
GroupBy(Of TSource, TKey, TElement)(IEnumerable(Of TSource), Func(Of TSource, TKey), Func(Of TSource, TElement)).
标签: c# linq entity-framework group-by