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

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

相关推荐
星辰徐哥1 天前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene
leoufung1 天前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
hacker7071 天前
Visual Studio安装教程(C#开发版)
ide·c#·visual studio
SKY -dada1 天前
Understand 使用教程
开发语言·c#·流程图·软件构建·敏捷流程·代码复审·源代码管理
William_cl1 天前
【C#/.NET 进阶】ASP.NET 架构与最佳实践:DI 依赖注入(IoC 核心)从入门到避坑
c#·asp.net·.net
武藤一雄1 天前
WPF:MessageBox系统消息框
前端·microsoft·c#·.net·wpf
武藤一雄1 天前
WPF进阶:万字详解WPF如何性能优化
windows·性能优化·c#·.net·wpf·.netcore·鲁棒性
xiaogutou11212 天前
2026年历史课件PPT模板选购指南:教师备课效率与精度的平衡方案
开发语言·c#
Eiceblue2 天前
使用 C# 将 Excel 转换为 Markdown 表格(含批量转换示例)
开发语言·c#·excel
不会编程的懒洋洋2 天前
WPF XAML+布局+控件
xml·开发语言·c#·视觉检测·wpf·机器视觉·视图