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

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

相关推荐
玖玥拾10 小时前
Unity 3D 笔记(十二)Unity/C# Socket 网络笔记1
网络·unity·c#
EIP低代码平台11 小时前
EIP低代码平台 - 系统日志
低代码·c#·权限·工作流·netcore
玖玥拾11 小时前
Unity 3D 笔记(十五)Unity/C# Socket 网络笔记4
服务器·网络·unity·c#
EIP低代码平台20 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
心平气和量大福大1 天前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
-银雾鸢尾-1 天前
C#中HashTable相关方法
开发语言·c#
geovindu1 天前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
吴可可1231 天前
C# CAD二次开发中如何退出窗口
c#
影寂ldy1 天前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
ellis19701 天前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#