我正在尝试对ArrayList
of进行排序String
。
鉴于:
{A,C,AA,B,CC,BB}
Arraylist.Sort
给出:
{A,AA,B,BB,C,CC}
我需要的是:
{A,B,C,AA,BB,CC}
ArrayList list = new ArrayList {"A","C","AA","B","CC","BB"};
var sorted = list.Cast<string>()
.OrderBy(str => str.Length)
.ThenBy(str => str);
//LinqPad specific print call
sorted.Dump();
印刷:
A
B
C
AA
BB
CC
使用 Linq 更容易做到这一点:
string [] list = { "A","C","AA","B","CC","BB"};
var sorted = list.OrderBy(x=>x.Length).ThenBy(x=>x);
请注意,该OrderBy
方法返回一个新列表。如果要修改原始文件,则需要重新分配它:
list = list.OrderBy(x=>x.Length).ThenBy(x=>x).ToArray();
我建议使用该ToArray()
方法(或仅使用List<string>
ArrayList 的 instad)来利用OrderBy
andThenBy
函数。它看起来像这样:
list = list.OrderBy(/*Order it by length*/).ThenBy(/*Order alphabetically*/);
您可以创建一个IComparable
接收两个字符串的类,并按如下方式对它们进行排序:
if (a.Length == b.Length)
return String.Compare(a, b);
return a.Length.CompareTo(b.Length);
您可能还想处理null
案件。
这是一种老派,但是,我去了 IComparer Interface 。. .
public class SortAlphabetLength : System.Collections.IComparer
{
public int Compare(Object x, Object y)
{
if (x.ToString().Length == y.ToString().Length)
return string.Compare(x.ToString(), y.ToString());
else if (x.ToString().Length > y.ToString().Length)
return 1;
else
return -1;
}
}
然后测试它。. .
class Program
{
static void Main(string[] args)
{
ArrayList values = new ArrayList()
{
"A","AA","B","BB","C","CC"
};
SortAlphabetLength alphaLen = new SortAlphabetLength();
values.Sort(alphaLen);
foreach (string itm in values)
Console.WriteLine(itm);
}
}
输出:
A
B
C
AA
BB
CC