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

时间:2013-04-01 18:52:22

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

我有一张桌子

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

    }
}

2 个答案:

答案 0 :(得分:1)

创建一个类来保存结果:

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>,它存储每个值的计数,同时只查询一次数据源。

然后可以使用以下方法将其传递给View:

return View(result);

答案 1 :(得分:0)

如果我理解你的问题 -

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

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());
相关问题