【问题标题】:C# - linq order by certains ids (multiple) then order by something elseC# - linq 按某些 id 排序(多个),然后按其他排序
【发布时间】:2021-05-29 06:10:21
【问题描述】:

我有这个代码:

var lotResults = lotTypes.OrderByDescending(x => x.LotTypeId == 14 || x.LotTypeId == 9 || x.LotTypeId == 15).ThenBy(x => x.Position).ToList();

我要做的是让结果按 LotTypeId(14,然后 9,然后 15)的顺序返回,然后按位置顺序给我其余数据。

我的问题是我的结果总是显示 15、9 和 14,无论我有什么顺序或条件......我如何让它成为 14,然后是 9,然后是 14?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    你可以这样试试

    var lotResults = lotTypes
        .OrderByDescending(x => x.LotTypeId == 14)
        .ThenByDescending(x => x.LotTypeId == 9)
        .ThenByDescending(x => x.LotTypeId == 15)
        .ThenBy(x => x.Position)
        .ToList();
    

    【讨论】:

    【解决方案2】:

    使用LotTypeId 的重新映射来替代已接受答案的几个C# 8。 像这样重新映射LotTypeId

    14 -> 1
    9 -> 2
    15 -> 3
    others -> 4
    

    我们可以为LotTypeId 使用单个OrderBy

    LotTypeId 的内联重映射(最少代码行选项)

    var lotResults = lotTypes
        .OrderBy(x => x.LotTypeId switch { 14 => 1, 9 => 2, 15 => 3, _ => 4 })
        .ThenBy(x => x.Position)
        .ToList();
    

    使用重映射方法(跨多个 LINQ 表达式重用)

    var lotResults = lotTypes
        .OrderBy(x => RemapLotTypeId(x.LotTypeId))
        .ThenBy(x => x.Position)
        .ToList();
    
    private static int RemapLotTypeId(int lotTypeId) => lotTypeId switch { 14 => 1, 9 => 2, 15 => 3, _ => 4 };
    

    当您有超过 5 次重新映射时,您可能不想维护映射的值,只需要查找实际的键,在这种情况下是 14, 9, 15。这可以使用List 解决。此映射将从零开始:14 -> 0 ... 其他 -> 3

    var lotResults = lotTypes
        .OrderBy(x => RemapLotTypeIdUsingList(x.LotTypeId))
        .ThenBy(x => x.Position)
        .ToList();
    
    private static readonly IList<int> LotTypeIds = new List<int> { 14, 9, 15 }.AsReadOnly();
    
    private static int RemapLotTypeIdUsingList(int keyToFind)
    {
        var sortKey = LotTypeIds.IndexOf(keyToFind);
        return sortKey < 0 ? LotTypeIds.Count : sortKey;
    }
    

    所有方法都在我的电脑上进行了测试和验证。

    【讨论】:

      猜你喜欢
      • 2015-10-06
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      相关资源
      最近更新 更多