[英]Using LINQ to count value frequency and display in MVC View
I have a table 我有桌子
ID|VALUE ID | VALUE
VALUE an integer field with possible values 0 - 1. How can I return the count of each value? VALUE一个可能值为0-1的整数字段。如何返回每个值的计数?
I'm trying to return the result in the below view - repository(repository.paths) 我试图在下面的视图中返回结果-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 );
}
}
}
Create a class to hold your result: 创建一个类来保存您的结果:
public class ViewModelData{
public int Key{ get; set; }
public int Count { get; set; }
}
Then in your controller 然后在您的控制器中
var result = repository.Paths.GroupBy(x => x.Value)
.Select(x => new ViewModelData{ Key = x.Key,
Count = x.Count())
.ToList();
This creates an IEnumerable<ViewModelData>
which stores the count of each value whilst only querying the data source once. 这将创建一个
IEnumerable<ViewModelData>
,它存储每个值的计数,而仅查询数据源一次。
This can then be passed to the View using: 然后可以使用以下命令将其传递到视图:
return View(result);
If I understand your question - 如果我理解您的问题-
You are trying to iterate through the results to find the counts and return the number of each to the view - 您正在尝试遍历结果以找到计数并将每个计数返回到视图中-
return(repository.Paths.Where(p => p.VALUE == 0).Count());
or 要么
return(repository.Paths.Where(p => p.VALUE == 1).Count());
If you are trying to return the list of each - 如果您尝试返回每个列表-
return(repository.Paths.Where(p => p.VALUE == 0).ToList());
or 要么
return(repository.Paths.Where(p => p.VALUE == 1).ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.