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

一、场景

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

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

二、代码

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();

你可能感兴趣的:(C#基础,c#,linq,开发语言)