1
votes

New to MVC and Linq.

I'm was able to display all records just fine but now I was trying to get a count of records by name and just select 2 fields:Name and Count

I thought I should create a new ViewModel, fill the Name,Count and send it to the view.

public ActionResult Index()
    {
        var load =
            db.loadingPPHs.Where(s => s.WORKDAY == db.loadingPPHs.Max(x => x.WORKDAY))
                .GroupBy(fu => fu.TMNAME)
                .Select(g => new {Name = g.Key, Count = g.Count()}).ToList();


        var viewModel = new loadingViewModel
        {
            LoadingListCount = load
        };

        return View(viewModel);
    }

The linq above works as expected. ViewModel:

public class loadingViewModel
    {

        public IEnumerable<LoadingListCount> LoadingListCount { get; set; }


    }

    public class LoadingListCount
    {

        public string Name{ get; set; }
        public int Count { get; set; }

    }

However, I'm getting an error. Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

I have trying converting the query to list and to IEnumerable but no luck. I've searched around other posts but I have not have luck with them.

3

3 Answers

4
votes

You are getting the error because of two main things, first one is the Linq produces a collection of an anonymous type, and the attached .ToList() gives you the result as List of anonymous type objects. But the expected result would be of type IEnumerable<LoadingListCount> so here we need to do few changes, First of all, we have to create an object of type LoadingListCount now the Linq will give you the output as expected, But the attached .ToList() will convert them to List<LoadingListCount> to avoid that we have to remove them as well. Finally, the query will look like the following:

var load = db.loadingPPHs.Where(s => s.WORKDAY == db.loadingPPHs.Max(x => x.WORKDAY))
                         .GroupBy(fu => fu.TMNAME)
                         .Select(g => new LoadingListCount {Name = g.Key, Count = g.Count()})
3
votes
.Select(g => new {Name = g.Key, Count = g.Count()})

produces objects of anonymous type, and puts them into a list. Since you need IEnumerable<LoadingListCount>, not IEnumerable<SomeAnonymousType> create instances of LoadingListCount instead by specifying the type in the invocation of new operator:

.Select(g => new LoadingListCount {Name = g.Key, Count = g.Count()})
1
votes

Your query is creating a collection of anonymous objects - you need to project your query into your model

IEnumerable<LoadingListCount> load = 
    db.loadingPPHs.Where(s => s.WORKDAY == db.loadingPPHs.Max(x => x.WORKDAY))
        .GroupBy(fu => fu.TMNAME)
        .Select(g => new LoadingListCount { Name = g.Key, Count = g.Count() })
var viewModel = new loadingViewModel
{
    LoadingListCount = load
};