Linq 按字符串排序不起作用

tco*_*ode 3 linq linq-to-entities predicate sql-order-by

我不明白为什么这段代码不会按字符串名称对我的数据列表进行排序。

public class GroupedRow
{
    public int id { get; set; }
    public string label { get; set; }
    public decimal SumOfDays { get; set; }
}

var data = _dataService.GetData();

List<GroupedRow> result = data
    .GroupBy(l => l.listItemID.Value)
    .Select(cl => new GroupedRow
    {
        label = cl.First().ListItem.description,
        SumOfDays = cl.Sum(c => c.timeAssigned.Value) / 8.0m
    }).ToList();

result.OrderByDescending(x => x.label).ToList();
Run Code Online (Sandbox Code Playgroud)

我试图按标签(字符串)对列表进行排序,但是,它永远不起作用。

谁能看到我做错了什么吗?

提前致谢。

小智 8

您正在对列表进行排序并使用创建新列表,ToList()但您没有为任何内容分配返回值,因此您会丢失它。Eiter 通过以下方式修复它:

result = result.OrderByDescending(x => x.label).ToList();
Run Code Online (Sandbox Code Playgroud)

或者

List<GroupedRow> result = data
    .GroupBy(l => l.listItemID.Value)
    .Select(cl => new GroupedRow
    {
        label = cl.First().ListItem.description,
        SumOfDays = cl.Sum(c => c.timeAssigned.Value) / 8.0m
    })
    .OrderByDescending(x => x.label)
    .ToList();
Run Code Online (Sandbox Code Playgroud)