5

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?

4

2 回答 2

2

您需要创建一个,而不是创建匿名类型Recipe

select new Recipe // Use constructor or object initiailizer here
                 {
                     ID = hh.Key.IDRecipe,
                     Score = hh.Sum(s => s.Score)
                 }).OrderByDescending(i => i.Score))
                 .ToList(); // To make your List<T>
于 2013-04-18T22:48:17.847 回答
2

您应该创建一个新类RecipeViewModel(或RecipeDto)来捕获结果:

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

但你说

我需要它是食谱类型

这让我怀疑您需要提供更多(或全部)数据Recipe。因此,您可能应该深刻地重构查询。如果是这样,您仍然不能使用Recipe该类本身,因为它没有Score属性:

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

假设有一个导航属性Recipe.StarRatings。如果没有,您应该使用一个join声明来包含评级。(或引入导航属性)。

于 2013-04-18T23:27:56.060 回答