Lambda表达式,只选择包含某些产品的类别
本文关键字:包含某 表达式 选择 Lambda | 更新日期: 2023-09-27 18:14:21
我在MVC应用程序上有一个多级下拉菜单,我正试图按品牌,性别和类型对产品进行排序。我的菜单是这样的:
<li>Man
<ul>
<li><h2>By Type</h2></li>
<li>CATEGORY</li>
</ul>
<ul>
<li><h2>By Brand</h2></li>
<li>BRAND</li>
</ul>
</div>
</li>
<li>
<li>Woman
<ul>
<li><h2>Categories</h2></li>
<li>CATEGORY</li>
</ul>
<ul>
<li><h2>Brands</h2></li>
<li>BRAND</li>
</ul>
</div>
</li>
<li>
这是我的一个控制器:
public ActionResult Man(int type)
{
var productTypeModel = storeDB.Categories.Include("Products")
.Single(g => g.CategoryId == type);
return View(productTypeModel);
}
这是加载到菜单中的partialview:
@model IEnumerable<Store.Models.Category>
<ul>
<li><h2>By Type</h2></li>
@foreach (var type in Model)
{
<li>@Html.ActionLink(type.Name,
"Man", "Store",
new { Category = type.CategoryId }, null)
</li>
}
</ul>
是否有任何方法,我可以只显示类别和品牌,有与每个性别使用lambda表达式相关的产品?我的意思是,当我浏览男士产品时,我不希望"裙子"出现在"分类"栏,我也不希望一个品牌的男士产品出现在女士栏。
您可以使用GroupBy:
public ActionResult Menu()
{
var model =
from p in storeDB.Products.Include("Category").Include("Type")
group p by p.Gender
into genderGroup
select new MenuObject
{
Gender = genderGroup.Key,
Categories =
(
from p2 in genderGroup
group p2 by p2.Category
into categoryGroup
select categoryGroup.Key
),
Types =
(
from p3 in genderGroup
group p3 by p3.Type
into typeGroup
select typeGroup.Key
)
};
return View(model);
}
public class MenuObject
{
public string Gender { get; set; }
public IEnumerable<Category> Categories { get; set; }
public IEnumerable<Type> Types { get; set; }
}
然后在模板中:
@foreach (var item in Model)
{
<li>@item.Gender
<ul>
<li><h2>By Category</h2></li>
@foreach (var category in item.Categories)
{
<li>@Html.ActionLink(category.Name,
"ByCategory", "Store",
new {
Gender = item.Gender,
Category = category.ID,
}, null)</li>
}
</ul>
<ul>
<li><h2>By Type</h2></li>
@foreach (var type in item.Types)
{
<li>@Html.ActionLink(type.Name,
"ByType", "Store",
new {
Gender = item.Gender,
Type = type.ID,
}, null)</li>
}
</ul>
</li>
}
将产生如下内容:
<li>Man
<ul>
<li><h2>By Category</h2></li>
<li><a href="/Store/ByCategory/Man/2/">Sports</a></li>
<li><a href="/Store/ByCategory/Man/3/">Underwear</a></li>
</ul>
<ul>
<li><h2>By Type</h2></li>
<li><a href="/Store/ByType/Man/1/">Boxer Shorts</a></li>
<li><a href="/Store/ByType/Man/2/">Socks</a></li>
</ul>
</li>
<li>Woman
<ul>
<li><h2>By Category</h2></li>
<li><a href="/Store/ByCategory/Woman/1/">Running</a></li>
<li><a href="/Store/ByCategory/Woman/2/">Sports</a></li>
<li><a href="/Store/ByCategory/Woman/3/">Underwear</a></li>
</ul>
<ul>
<li><h2>By Type</h2></li>
<li><a href="/Store/ByType/Woman/2/">Socks</a></li>
<li><a href="/Store/ByType/Woman/3/">Bra</a></li>
</ul>
</li>