我有的列表是基于检查前4个值进行正确排序,但我需要列表中未预定义的任何其他值(并且不以CS开头)正如我在下面评论的那样优先考虑。非预定义的值可能总是以数值开头的任何东西,所以任何以1-9(1,2,3,4,5,6,7,8,9)开头的东西。C#:自定义顺序数组,扭曲:
我该如何自定义类似这样的东西?我是否应该专注于在单独的列表中重新定义以1-9开头的任何内容,或者有什么我可以使用的将代表“任何未定义的内容都在这里”谢谢!
更新:感谢您的帮助每个人,我称它为一个夜晚,并用Excel生成每个数字组合从0-9999开始00000001等以及000-,001-为3位数字去在古怪的CS#之前。很酷的是,该程序需要一两秒钟的时间来处理所有的事情,这看起来好像在做很多工作! (我想是的)我可以添加一个进度条!程序现在是229kb,但它的工作原理!有时你只需打破胶带。
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()
{
List<string> list = new List<string>()
{
"CS01",
"CS10",
"CS58",
"CS11",
"CS71",
"CS02",
"CS55",
"CS03",
"CS70",
"CS54",
"CS60",
//<---How to prioritize any value that is not predefined in list to show up here? such as 1234-444-555
"CS57",
};
_order = new Dictionary<string, int>();
for (int i = 0; i < list.Count; i++)
{
_order.Add(list[i], i);
}
}
public int Compare(string x, string y)
{
if (x.Length < 4 || y.Length < 4)
return x.CompareTo(y);
string xPrefix = x.Substring(0, 4);
string yPrefix = y.Substring(0, 4);
int xSequence;
int ySequence;
if (_order.TryGetValue(xPrefix, out xSequence)
&& _order.TryGetValue(yPrefix, out ySequence))
{
return xSequence.CompareTo(ySequence);
}
else
{
return x.CompareTo(y);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Replace("(", "");
textBox1.Text = textBox1.Text.Replace(")", "");
string[] items = textBox1.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Array.Sort<string>(items, 0, items.Length, new Comparer());
textBox2.Text = String.Join(Environment.NewLine, items);
}
}
}
您是否在寻找“自然排序”?有关讨论,请参阅http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html。 – 2010-02-23 13:51:07