C#基础:利用LINQ进行复杂排序

发布时间:2024年01月11日

一、场景

请你写出linq对表格排序,CODE=3排前面,其余按照CODE降序排序,CODE一样再按照字母升序排序

IDCODEVALUE
A00011A
A00021B
A00031C
A00042D
A00052E
A00062F
A00073G
A00083H
A00093I
A00104J

二、代码

using System;
using System.Collections.Generic;
using System.Linq;

class SortingDemo
{
    static void Main()
    {
        // 创建数据源
        var data = new[]
        {
            new { ID = "A0001", CODE = 1, VALUE = "A" },
            new { ID = "A0002", CODE = 1, VALUE = "B" },
            new { ID = "A0003", CODE = 1, VALUE = "C" },
            new { ID = "A0004", CODE = 2, VALUE = "D" },
            new { ID = "A0005", CODE = 2, VALUE = "E" },
            new { ID = "A0006", CODE = 2, VALUE = "F" },
            new { ID = "A0007", CODE = 3, VALUE = "G" },
            new { ID = "A0008", CODE = 3, VALUE = "H" },
            new { ID = "A0009", CODE = 3, VALUE = "I" },
            new { ID = "A0010", CODE = 4, VALUE = "J" }
        };

        // 使用LINQ进行排序
        var sortedData = data
                            .OrderByDescending(item => item.CODE == 3)
                            .ThenByDescending(item => item.CODE)
                            .ThenBy(item => item.VALUE)
                            .ToList();
        // 输出排序结果
        foreach (var item in sortedData)
        {
            Console.WriteLine($"ID: {item.ID}, CODE: {item.CODE}, VALUE: {item.VALUE}");
        }
    }
}

三、结果

ID: A0007, CODE: 3, VALUE: G
ID: A0008, CODE: 3, VALUE: H
ID: A0009, CODE: 3, VALUE: I
ID: A0010, CODE: 4, VALUE: J
ID: A0004, CODE: 2, VALUE: D
ID: A0005, CODE: 2, VALUE: E
ID: A0006, CODE: 2, VALUE: F
ID: A0001, CODE: 1, VALUE: A
ID: A0002, CODE: 1, VALUE: B
ID: A0003, CODE: 1, VALUE: C

四、思考

若再加大难度,ID=A0005的排第一,然后CODE=3排前面,其余按照CODE降序排序,再按照字母升序排序,如何写呢?

var sortedData = data.OrderByDescending(item=>item.ID=="A0005")
                    .ThenByDescending(item => item.CODE == 3)
                    .ThenByDescending(item => item.CODE)
                    .ThenBy(item => item.VALUE)
                    .ToList();

文章来源:https://blog.csdn.net/m0_67412019/article/details/135531517
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。