简体   繁体   中英

Using LINQ to count value frequency and display in MVC View

I have a table

ID|VALUE

VALUE an integer field with possible values 0 - 1. How can I return the count of each value?

I'm trying to return the result in the below view - 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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