一、场景
请你写出linq对表格排序,CODE=3排前面,其余按照CODE降序排序,CODE一样再按照字母升序排序文章来源:https://www.toymoban.com/news/detail-801759.html
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降序排序,再按照字母升序排序,如何写呢?文章来源地址https://www.toymoban.com/news/detail-801759.html
var sortedData = data.OrderByDescending(item=>item.ID=="A0005")
.ThenByDescending(item => item.CODE == 3)
.ThenByDescending(item => item.CODE)
.ThenBy(item => item.VALUE)
.ToList();
到了这里,关于C#基础:利用LINQ进行复杂排序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!