0

我有一张桌子

ID|值

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

    }
}
4

2 回答 2

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

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

return View(result);
于 2013-04-01T19:03:19.453 回答
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());
于 2013-04-01T19:07:36.833 回答