【问题标题】:EF Linq query to get count of categoriesEF Linq 查询以获取类别计数
【发布时间】:2016-06-17 19:00:20
【问题描述】:

在带有 EF 的 asp.net MVC 应用程序中,我将类别列表返回到多选框。

对于每个类别,我想计算数据库中出现的次数并将其显示在同一选择框中,例如 "Category A (Count: 77)"

这是我必须返回所有不同类别的代码:

private List<Categories> GetCategories()
{
    using (myEntities dc = new myEntities())
    {
        List<Categories> categoryList = dc.View.Select(
            t => new Categories
            {
                category = t.category,
                categoryOutput = t.category + "Count: "
            })
            .Distinct()
            .OrderBy(t => t.category)
            .ToList();

    return categoryList;
    }
}

public class Categories
{
    public string category { get; set; }
    public string categoryOutput { get; set; }
}

你能告诉我需要添加什么来计算每个类别的计数吗?

更新:

感谢 GroupBy 的解释! 它如何与多个属性一起使用,例如附加的“categoryCode”:

public class Categories { 
public string category { get; set; } 
public string categoryCode { get; set; } 
public string categoryOutput { get; set; } }

谢谢

【问题讨论】:

  • 试试categoryOutput = t.category.Distinct().Count()
  • @ShawnYan 这只会给你类别的数量,而不是每个类别中的项目数
  • @Rhumborl 我明白了,所以您需要 GroupBy 来分隔每个类别并从那里开始计数。我的错误:-)
  • @ShawnYan 完全正确 :) 很高兴帮助您更好地理解

标签: asp.net-mvc entity-framework linq


【解决方案1】:

你需要GroupBy()

List<Categories> categoryList = dc.View
        .GroupBy(t => t.category)
        .Select(t => new Categories
        {
            // t is now essentially an enumerable with a Key property
            category = t.Key, // Key is what we grouped by (category)
            categoryOutput = t.Key + "Count: " + t.Count().ToString()
        })
        //.Distinct() // no need for this now
        .OrderBy(t => t.category)
        .ToList();

【讨论】:

  • 感谢您的解决方案。如果我需要包含更多类属性怎么办?喜欢:public class Categories { public string category { get; set; } public string categoryCode { get; set; } public string categoryOutput { get; set; } }
猜你喜欢
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多