linq group by和order by by list?

时间:2013-06-17 12:38:53

标签: c# linq group-by sql-order-by

我有一个列表(avgEnergyObj),如

Timestamp | MeterID | Energy
----------------------------
190990001 |    1    | 98090.0
190990003 |    2    | 98909.3
190990002 |    2    | 99000.3
190990004 |    1    | 99900.9

我希望按时间戳排序,按照米ID分组 -

Timestamp | MeterID | Energy
----------------------------
190990001 |    1    | 98090.0
190990003 |    2    | 99000.3
190990002 |    1    | 98909.3
190990004 |    2    | 99900.9

我写了一些(不工作)错误 -

List<FetchingEnergy> avgEnergyObj2 =
    avgEnergyObj.GroupBy(p => p.MeterId)
                .Select(group =>
                    new {
                        meterID = group.Key,
                        FetchingEnergy = group.OrderBy(x => x.TimeStamp)
                    })
                .OrderBy(group => group.FetchingEnergy.First().TimeStamp);

1 个答案:

答案 0 :(得分:1)

var sortedList = avgEnergyObj
    .OrderBy(x => x.MeterId)
    .ThenBy(x => x.TimeStamp)
    .ToList();