C#:如何仅按前 4 位数字以预定义的自定义顺序对数组进行排序?

标签 c# sorting

我想创建一个简单的 C# GUI,其中包含一个文本框,供用户将内容粘贴到其中并重新复制排序后的内容。

例如,用户会将其粘贴到框中:

part #        QTY
CS01-111-111  3
CS02-222-222  3
CS03-333-111  3
CS03-333-333  3 

然后我希望程序像这样对粘贴到其中的任何内容进行排序。仅按前 4 位排序,但保留其后的 QTY 值:

part #        QTY
CS03-333-111  3
CS03-333-333  3
CS01-111-111  3
CS02-222-222  3

我有一些 C# 代码可以帮助我执行此操作,但它一直处于锁定状态。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public class Comparer : IComparer<string>
        {

            private Dictionary<string, int> _order;

            public Comparer()
            {
                _order = new Dictionary<string, int>();
                _order.Add("CS01", 1);
                _order.Add("CS58", 2);
                _order.Add("CS11", 3);
            }

            public int Compare(string x, string y)
            {
                if (x.Length < 4 || y.Length < 4)
                    return x.CompareTo(y);
                if (!_order.ContainsKey(x.Substring(0, 4)) || !_order.ContainsKey(y.Substring(0, 4)))
                    return x.CompareTo(y);
                return _order[x.Substring(0, 4)].CompareTo(_order[y.Substring(0, 4)]);
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string[] items = textBox1.Text.Split(Environment.NewLine.ToCharArray());
            Array.Sort<string>(items, 0, items.Length, new Comparer());
            textBox1.Text = String.Join(Environment.NewLine, items);
        }
    }
}

有什么办法可以解决吗?

最佳答案

创建一个比较器,其中包含一个字典,用于确定字符串的排序方式:

public class Comparer : IComparer<string> {

   private Dictionary<string, int> _order;

   public Comparer() {
      _order = new Dictionary<string, int>();
      _order.Add("03-33", 1);
      _order.Add("01-11", 2);
      _order.Add("02-22", 3);
   }

   public int Compare(string x, string y) {
      return _order[x.Substring(2, 5)].CompareTo(_order[y.Substring(2, 5)]);
   }

}

然后你可以在Array.Sort方法中使用比较器

string[] items = TheTextBox.Text.Split(new String[]{ Environment.NewLine});
Array.Sort<string>(items, 1, items.Length - 1, new Comparer());
TheTextBox.Text = String.Join(Environment.NewLine, items);

关于C#:如何仅按前 4 位数字以预定义的自定义顺序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308312/

相关文章:

c# - 尽管 PerformanceCounter 类别存在,但它并不存在

c++ - 排序插入到小(255 个元素)列表中

sorting - 在 Google 表格中的过滤器 View 中排序时,ArrayFormula 列消失

java - 使用比较器的意外输出

c# - 从客户端进行身份验证后,ServiceStack session 未保存

C# .net 3.5 进程间通信验证子进程是否启动正常

c# - 从 USB 条码设备 C# 读取数据的标准方法

c# - Entity Framework 的原子增量

list - 根据某些元素对列表进行排序

javascript - MySQL 中的日期格式用于通过 AngularJS 日期过滤器进行过滤