从List of String获取特定列的计数

时间:2016-04-15 17:24:42

标签: asp.net-mvc-4 c#-4.0

如何在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

1 个答案:

答案 0 :(得分:1)

首先,您需要Region的视图模型,其中包含NameCount属性

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
    }
}