LINQ 匿名类型没有给出我需要的列表

问题描述 投票:0回答:2

我正在对对象调用

Recipe
进行 LINQ 查询,需要按其分数排序。一开始,我有一个
IEnumerable
类型的
Recipe
(已使用搜索条件过滤),称为
selectedRecipies

然后,在我朋友google的帮助下,我使用匿名类型完成了这个查询:

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

而且我认为它有效...我的问题是,就我而言,我需要它是

Recipe
类型,而
finalQuery
似乎是
IEnumerable<'a>
类型,其中
a
是匿名类型...

如何在不干扰 OrderByDescending 的情况下获得 Recipe 类型的

List<>

c# asp.net-mvc linq anonymous-types
2个回答
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
语句来包含评级。 (或引入导航属性)。


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>
© www.soinside.com 2019 - 2024. All rights reserved.