【问题标题】:Linq orderby calculationLinq orderby 计算
【发布时间】:2011-11-21 06:37:36
【问题描述】:

我前段时间为一个工具构建了一个 SQL 查询,我正在 MVC 中重新制作该工具并使用 LINQ to Entities。

我似乎不知道如何通过按工时及其测试价值对我的汽车进行加权来对我的品牌列表进行排序。

这是我在旧工具中的 SQL 查询:

    SELECT Brand.ID, SUM(Car.EstManHours) - SUM(Car.EstManHours) * CAST(AVG(1.00 * TestingStatus.Value) AS DECIMAL(9 , 2)) / 100 AS Weighting
FROM TestingStatus INNER JOIN Car ON TestingStatus.ID = Car.StatusID
    INNER JOIN Team ON Car.TeamID = Team.TeamID 
    RIGHT OUTER JOIN Brand 
    LEFT OUTER JOIN SubCategory ON Brand.ID = SubCategory.BrandID ON Car.SubCategoryID = SubCategory.ID 
WHERE (Car.IsPunted == 'False')
GROUP BY Brand.YearID, Brand.FeatID
HAVING (Brand.YearID = @BrandYearID)
ORDER BY Weighting DESC

我已经尝试过了,但是无论我将降序还是升序放在列表中实际上并没有改变,它保持按 Id 排序:

var brands = (from b in _context.Brands
            join s in _context.SubCategorys on f.Id equals s.BrandId
            join c in _context.Cars on s.Id equals c.SubCategoryId
            where (f.YearId == yearId && c.IsPunted == false)
            orderby (c.ManHoursEst - (c.ManHoursEst * c.TestingStatu.Value / 100)) descending 
            select b).Distinct().ToList();

非常感谢有关此转换的帮助!

谢谢。

编辑:

我现在正试图让 order by 和 group by 正常工作。 以下查询列出了大量重复项并且没有正确排序,因为我认为我的权重没有正确完成。

var brands = (from b in _context.Brands
            join s in _context.SubCategorys on f.Id equals s.BrandId
            join c in _context.Cars on s.Id equals c.SubCategoryId
            where (f.YearId == yearId && c.IsPunted == false)
            let weighting = c.ManHoursEst - (c.ManHoursEst * c.TestingStatu.Value / 100)
            orderby weighting descending 
            group b by b.Id).SelectMany(x=>x).ToList();

有什么想法吗?

【问题讨论】:

  • 您的原始查询正在执行分组 - 您的 LINQ 查询不是。
  • @LanFeusT :为了可读性,我会使用“let”子句来计算权重,然后按“权重”排序。它不会改变性能或输出,只是带有公式的 order by 子句伤害了我的眼睛:-P
  • @Tipx 绝对是个好主意! ^^ 谢谢会做。

标签: c# sql linq sorting


【解决方案1】:

Distinct 不保留排序。那是你的问题。

您可以在 SQL 中执行 group by 之类的操作,以模仿 Distinct 并在服务器端执行所有操作。

【讨论】:

  • 事实上,进行 group by 不会“模仿 distinct”,这将是他查询的正确翻译,因此他的 distinct 将停止模仿他的 group by! ;-)
  • 有没有办法可以将该分组转换回 List?由于执行 group b by c.ManHoursEst - (c.ManHoursEst*c.TestingStatu.Value/100) 将其转换为 List> ?
  • @LanFeusT:当你的查询正确时,你可以说SelectMany(g => g).ToList()。但是您的查询显然是错误的。你为什么按这个分组?
  • 好的,我正在尝试按我的 Brand.Id 分组并按权重排序。但很明显我做错了什么 xD var brands = (from b in _context.Brands join s in _context.SubCategorys on b.Id equals s.BrandId join c in _context.Cars on s.Id equals c.SubCategoryId where (b.YearId == yearId && c.IsPunted == false) let weighting = c.ManHoursEst - (c.ManHoursEst*c.TestingStatu.Value/100) orderby weighting descending group b by b.MilestoneId).SelectMany(g=>g).ToList(); 这给了我一个包含很多重复项且没有正确排序的列表。
  • 我会将此答案标记为正确,因为这绝对是我的问题。我无法正确查询,而是使用我的 SQL 查询并将其转储到存储过程中,这使得这一切变得更加容易。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2020-06-10
相关资源
最近更新 更多