NET 中,你可以使用LINQ 根据指定字段排序

在.NET 中,你可以使用LINQ(Language Integrated Query)来实现根据指定顺序对集合进行

排序。以下是一个示例代码,其中假设你有一个包含省、市、县信息的类:

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;

public class Address
{
    public string Province { get; set; }
    public string City { get; set; }
    public string County { get; set; }
}

class Program
{
    static void Main()
    {
        List<Address> addresses = new List<Address>
        {
            new Address { Province = "广东", City = "深圳", County = "南山区" },
            new Address { Province = "广东", City = "广州", County = "天河区" },
            new Address { Province = "北京", City = "北京", County = "朝阳区" },
            new Address { Province = "广东", City = "深圳", County = "福田区" }
        };

        string[] order = { "广东", "深圳", "南山区" };

        var sortedAddresses = addresses.OrderBy(addr =>
        {
            int provinceIndex = Array.IndexOf(order, addr.Province);
            int cityIndex = Array.IndexOf(order, addr.City);
            int countyIndex = Array.IndexOf(order, addr.County);
            return (provinceIndex, cityIndex, countyIndex);
        });

        foreach (var address in sortedAddresses)
        {
            Console.WriteLine($"{address.Province} - {address.City} - {address.County}");
        }
    }
}

上述代码中,我们首先定义了一个Address 类来表示地址信息,然后创建了一个包含Address 对象的集合。

接着,我们定义了一个字符串数组order,其中包含了我们希望按照的排序顺序。

在LINQ 查询中,我们使用OrderBy 方法来排序addresses 集合。在排序的过程中,我们通过Array.IndexOf 方法获取每个地址信息在order 数组中的索引,然后返回一个包含省、市、县排序索引的元组。

bash 复制代码
北京 - 北京 - 朝阳区
广东 - 广州 - 天河区
广东 - 深圳 - 福田区
广东 - 深圳 - 南山区

最终,我们将排序后的地址信息打印出来。请根据你的实际需求修改Address 类和order 数组,

以适应你的数据和排序要求。

相关推荐
FL16238631297 小时前
[C#][winform]segment-anything分割万物部署onnx模型一键抠图演示
开发语言·c#
love530love9 小时前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
bcbobo21cn10 小时前
C# byte类型和byte数组的使用
开发语言·c#·字节数组·byte类型
月巴月巴白勺合鸟月半12 小时前
一次PDF文件的处理(一)
pdf·c#
大鹏说大话13 小时前
Java 锁膨胀机制深度解析:从偏向锁到重量级锁的进化之路
开发语言·c#
武藤一雄15 小时前
WPF处理耗时操作的7种方法
microsoft·c#·.net·wpf
武藤一雄16 小时前
C#常见面试题100问 (第一弹)
windows·microsoft·面试·c#·.net·.netcore
l1t18 小时前
DeepSeek总结的用 C# 构建 DuckDB 插件说明
前端·数据库·c#·插件·duckdb
iReachers18 小时前
恒盾C#混淆加密大师 1.4.5 最新2026版本发布 (附CSDN下载地址)
c#·c#混淆·c#加密·wpf加密·winform加密
历程里程碑19 小时前
43. TCP -2实现英文查中文功能
java·linux·开发语言·c++·udp·c#·排序算法