我想创建一个带有文本框的简单C#GUI,供用户将内容粘贴到其中并重新复制已排序的内容.
例如,用户会将其粘贴到框中:
part # QTY
CS01-111-111 3
CS02-222-222 3
CS03-333-111 3
CS03-333-333 3
Run Code Online (Sandbox Code Playgroud)
然后我想让程序对这样粘贴的东西进行排序.仅按前4位排序,但保留后面的QTY值:
part # QTY
CS03-333-111 3
CS03-333-333 3
CS01-111-111 3
CS02-222-222 3
Run Code Online (Sandbox Code Playgroud)
我有一些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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以解决它吗?
创建一个比较器,其中包含您希望字符串排序方式的字典:
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)]);
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1902 次 |
| 最近记录: |