订单的LINQ语法来自子集合的最大SUM值

时间:2015-08-27 16:10:29

标签: c# linq entity-framework entity-framework-6

我有以下记录

User
---------------
UserID | Name
---------------
   1   | Johan
   2   | Rick
---------------

UserDetail
----------------------------------
UserDetailID | UserID | Percentage
----------------------------------
      1      |    1   |     10
      2      |    1   |     30
      3      |    2   |     50
      4      |    2   |     10
----------------------------------

基本上我想按每个UserID和订单按最大总百分比计算。

在TSQL中:

SELECT
    User.UserID
FROM
    User
    LEFT JOIN
    (
        SELECT
            SUM(Percentage) [Total],
            UserID
        FROM
            UserDetail
        GROUP BY
            UserID
    ) qry ON
        User.UserID = qry.UserID
ORDER BY
    qry.Total DESC

我目前的代码:

var orderedList = user.SelectMany(s => s.UserDetails).Sum(s => s.Percentage); // <-- I have no idea what I'm doing

1 个答案:

答案 0 :(得分:3)

听起来你根本不想使用SelectMany - 你只需要每个用户一行。我怀疑你想要:

var orderedList = users.OrderByDescending(user => user.UserDetails.Sum(d => d.Percentage));