繁体   English   中英

使用LINQ计数值频率并在MVC视图中显示

[英]Using LINQ to count value frequency and display in MVC View

我有桌子

ID | VALUE

VALUE一个可能值为0-1的整数字段。如何返回每个值的计数?

我试图在下面的视图中返回结果-repository(repository.paths)

namespace CessationPath.Controllers
{
    public class SampleController : Controller
    {
        private IPathsRepository repository;

        public SampleController(IPathsRepository repoParam) {
            repository = repoParam;
        }

        //
        // GET: /Sample/

        public ActionResult Index()
        {
            return View(repository.Paths   );
        }

    }
}

创建一个类来保存您的结果:

public class ViewModelData{
    public int Key{ get; set; }
    public int Count { get; set; }
}

然后在您的控制器中

var result = repository.Paths.GroupBy(x => x.Value)
                             .Select(x => new ViewModelData{ Key = x.Key, 
                                                             Count = x.Count())
                             .ToList();

这将创建一个IEnumerable<ViewModelData> ,它存储每个值的计数,而仅查询数据源一次。

然后可以使用以下命令将其传递到视图:

return View(result);

如果我理解您的问题-

您正在尝试遍历结果以找到计数并将每个计数返回到视图中-

return(repository.Paths.Where(p => p.VALUE == 0).Count());

要么

return(repository.Paths.Where(p => p.VALUE == 1).Count());

如果您尝试返回每个列表-

return(repository.Paths.Where(p => p.VALUE == 0).ToList());

要么

return(repository.Paths.Where(p => p.VALUE == 1).ToList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM