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 IEnumberable
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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With