Linq orderby计算

时间:2011-09-20 16:57:27

标签: c# sql linq sorting

我有一个我之前为工具构建的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();

非常感谢您对此次转化的帮助!

感谢。

编辑:

我现在正试图通过分组获取订单以正常工作。 以下查询列出了大量的重复项,而没有正确排序,因为我认为我的权重没有正确完成。

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

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

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

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