本文介绍: 请你写出linq对表格排序,CODE=3排前面,其余按照CODE降序排序,CODE一样再按照字母升序排序IDCODEVALUEA00011AA00021BA00031CA00042DA00052EA00062FA00073GA00083HA00093IA00104J。

一、场景

请你写出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();

原文地址:https://blog.csdn.net/m0_67412019/article/details/135531517

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_56288.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注