如何按数字顺序按最短优先顺序对多个数字字符串整数进行排序? C#

问题描述 投票:0回答:2

我在数据库中保存了一个实体,该实体具有 2 个相关属性:代码和编号。

数字只是 1 到 99 之间的整数,而代码是字符串表示形式,如“01”到“99”

问题是某些子实体的代码如“0103”或“3301”,这只是父实体的代码+它自己的代码。

所有实体都保存在一张表上,仅通过代码长度表示有 3 级层次结构“00”为 1 级,“0000”为 2 级,“000000”为 3 级。

我想以这样的方式订购它们

  • 名称 - 01
  • 名称 - 010201
  • 名称 - 0103
  • 名称 - 02
  • 名称 - 0201
  • 名称 - 04

等等...

首先是“01”的实体,后面是以“01”开头的实体,每个实体下面都是以“01xx”开头的实体,类似于树形层次结构。

请注意,我正在使用 EFcore 5、.NET 5 和 C# 9

我现在拥有的只是

var SearchQuery = _appDbContext.Regions.AsNoTracking().AsQueryable().OrderBy(r => r.Code);

然后我使用该查询来生成我的 DTO

ResultData = await SearchQuery.Select(r => new DTO
                {
                    Id = r.Id,
                    NameCode = r.Name + " - " + r.Code
                }).ToListAsync();

我应该使用自定义比较器还是其他东西?或者这种方法是否令人满意?

c# linq asp.net-core
2个回答
1
投票

使用 IComparable :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication20
{
    class Program
    {
        static void Main(string[] args)
        {

            string[] array = {"name - 01", "name - 010201", "name - 0103", "name - 02", "name - 0201", "name - 04"};
            string[] sorted = array.Select(x => new Sort(x)).OrderBy(x => x).Select(x => x.numericStr).ToArray();
        }
    }
    public class Sort : IComparable<Sort>
    {
        public string numericStr { get; set; }
        string[] split { get; set; }
        string number { get; set; }
        public Sort(string input)
        {
            numericStr = input;
            split = input.Split(new char[] { ' ' }).ToArray();
        }
        public int CompareTo(Sort other)
        {
            int minSize = Math.Min(split.Length, split.Length);
            for(int i = 0; i < minSize; i++)
            {
                int c = split[i].CompareTo(other.split[i]);
                if (c != 0) return c;
            }
            return split.Length.CompareTo(other.split.Length);

        }
    }
    
}

0
投票

我设法创建一个函数,收集 3 个不同列表中的 1、2、3 级实体(应用过滤器后),然后循环遍历它不到几次,并根据正确的顺序将它们插入到

List<Entity>

但是 @CharlesMager 向我澄清,由于 Code 属性没有任何空格,正常的

OrderBy(r => r.Code)
将具有完全相同的结果。

换句话说:

OrderBy(r => r.Code)
不会像我之前想象的那样对
01
02
01xx
中的字符串进行排序; 相反,它会按正确的顺序对它们进行排序,例如
01
01xx
02
02xx
等等。

© www.soinside.com 2019 - 2024. All rights reserved.