我想创建一个简单的 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/