如何在foreach
循环
模型
public class Region
{
public int LanguageId { get; set; }
public string LanguageName { get; set; }
}
查看模型
public class ViewModel
{
public List<Region> Regions { get; set; }
}
数据
0 LanguageId = 1 LanguageName = "English"
1 LanguageId = 2 LanguageName = "German"
2 LanguageId = 3 LanguageName = "French"
3 LanguageId = 1 LanguageName = "English"
4 LanguageId = 1 LanguageName = "English"
我想要LanguageId
的计数,如果它大于1我想要应用某些条件
查看
foreach (var item in Model.Regions)
{
if (Model.Regions[item].LanguageId.Count > 1)
{
// do something
}
}
要求是显示
English (apply condition here because there are more that one)
French
German
答案 0 :(得分:1)
首先,您需要Region
的视图模型,其中包含Name
和Count
属性
public class RegionVM
{
public string Name { get; set; }
public int Count { get; set; }
}
然后在控制器中使用.GroupBy()
按名称对区域进行分组
IEnumerable<Region> regions = .... // your query to get the regions
IEnumerable<RegionVM> model = regions.GroupBy(x => x.LanguageName).Select(x > new RegionVM()
{
Name = x.Key,
Count = x.Count()
}.AsEnumerable();
return View(model)
并在视图中
@model IEnumerable<RegionVM>
@foreach(var language in Model)
{
<div>@language.Name</div>
if(language.Count > 1)
{
// do something
}
}