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

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

相关推荐
Traced back5 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
yj爆裂鼓手6 小时前
c#万能变量
开发语言·c#
不绝1916 小时前
C#进阶:委托
开发语言·c#
喜欢喝果茶.6 小时前
跨.cs 文件传值(C#)
开发语言·c#
就是有点傻6 小时前
C#中如何和欧姆龙进行通信的
c#
黑夜中的潜行者15 小时前
构建高性能 WPF 大图浏览器:TiledViewer 技术解密
性能优化·c#·.net·wpf·图形渲染
LongtengGensSupreme16 小时前
C# 中监听 IPv6 回环地址(Loopback Address)----socket和tcp
c#·ipv6 回环地址
就是有点傻16 小时前
C#中如何和西门子通信
开发语言·c#
海底星光16 小时前
c#进阶疗法 -jwt+授权
c#
液态不合群16 小时前
如何提升 C# 应用中的性能
开发语言·算法·c#