Search code examples
c#asp.net-mvclinqanonymous-types

LINQ anonymous type not giving the list I need


I'm in the process of doing a LINQ query of an object call Recipe that need to be ordered by it's score. In the beginning, I have a IEnumerable of type Recipe (already filtered with the search criteria) called selectedRecipies

Then, with the help of my friend google, I have done this query using an anonymous type:

var finalQuery = ((from h in db.StarRatings
                   where selectedRecipies.Any(sr => sr.IDRecipe == h.IDRecipe)
                   group h by new { h.IDRecipe } into hh
                   select new
                     {
                         hh.Key.IDRecipe,
                         Score = hh.Sum(s => s.Score)
                     }).OrderByDescending(i => i.Score));

And I think it work... My problem is that for my view, I need it to be of type Recipe and finalQuery seems to be of type IEnumerable<'a> where a is the anonymous type...

How can I get a List<> of type Recipe without disturbing the OrderByDescending?


Solution

  • You should create a new class RecipeViewModel (or RecipeDto) to capture the results:

    select new RecipeViewModel
     {
         hh.Key.IDRecipe,
         Score = hh.Sum(s => s.Score)
     }).OrderByDescending(i => i.Score));
    

    But you say

    I need it to be of type Recipe

    which makes me suspect you need more (or all) data of Recipe to be presented. So you probably should restructure the query profoundly. And if so, you still can't use the Recipe class itself, because it has no Score property:

    from r in db.Recipes
    where // .....  (do your filtering here)
    select new RecipeViewModel
      {
          Id = r.Id,
          // ... more recipe properties
          Score = r.StarRatings.Sum(rating => rating.Score)
      }
    

    assuming that there is a navigation property Recipe.StarRatings. If not, you should use a join statement to include the ratings. (or introduce the navigation property).