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 数组,

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

相关推荐
bugcome_com3 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中4 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
bugcome_com6 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
懒人咖17 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com17 小时前
深入了解 C# 编程环境及其开发工具
c#
wfserial19 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师21 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao201921 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#
lucky67071 天前
Spring Boot集成Kafka:最佳实践与详细指南
spring boot·kafka·linq
啦啦啦_99991 天前
Redis-5-doFormatAsync()方法
数据库·redis·c#