如何使用 LINQ 对多个字段进行排序

本文关键字:字段 排序 何使用 LINQ | 更新日期: 2023-09-27 18:36:56

有人可以帮我展示如何对 LINQ 表达式进行排序吗?

我有以下几点:

 .OrderByDescending(item => item.RowKey)
 .Select((t, index) => new City.Grid()
           {
               PartitionKey = t.PartitionKey,
               RowKey = t.RowKey,
               Row = index + 1,
               ShortTitle = t.ShortTitle,
           })

我想做的是对以下内容进行排序:

1) 前四个字符或字段 行键
2) 短标题

我不确定如何对

几个字符进行排序,也不确定如何进行二次排序。

如何使用 LINQ 对多个字段进行排序

对于前四个字符,请将其包含在现有语句中,然后添加 ShortTitle

.OrderByDescending(item => item.RowKey.Substring(0,4))
.ThenBy(item => item.ShortTitle)
您可以使用

OrderByDescending(...)。然后由()...

.OrderByDescending(item => item.RowKey.Substring(0, Math.Min(4, item.RowKey.Length)))
.ThenBy(item => item.ShortTitle)
.Select((t, index) => new City.Grid()
       {
           PartitionKey = t.PartitionKey,
           RowKey = t.RowKey,
           Row = index + 1,
           ShortTitle = t.ShortTitle,
       })

呵托比

您可以使用

ThenByThenByDescending添加第二个排序键。

可以使用Enumerable.ThenBy 方法

.OrderByDescending(item => item.RowKey)
.ThenByDescending(item => item.ShortTitle)
 .Select((t, index) => new City.Grid()
           {
               PartitionKey = t.PartitionKey,
               RowKey = t.RowKey,
               Row = index + 1,
               ShortTitle = t.ShortTitle,
           })

对于第一个要求,按子字符串排序,您可以将Substring传递到表达式树中:

.OrderByDescending(item => item.RowKey.Substring(0, 4))

(但请注意越界例外情况。

对于辅助排序,请使用 ThenBy() 方法:

.ThenBy(item => item.ShortTitle)

组合的:

.OrderByDescending(item => item.RowKey.Substring(0, 4))
.ThenBy(item => item.ShortTitle)
.Select((t, index) => new City.Grid()
       {
           PartitionKey = t.PartitionKey,
           RowKey = t.RowKey,
           Row = index + 1,
           ShortTitle = t.ShortTitle,
       })