4

我正在尝试对ArrayListof进行排序String

鉴于:

{A,C,AA,B,CC,BB}

Arraylist.Sort给出:

{A,AA,B,BB,C,CC}

我需要的是:

{A,B,C,AA,BB,CC}
4

5 回答 5

12
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 
于 2013-01-10T14:37:22.553 回答
4

使用 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();
于 2013-01-10T14:37:56.127 回答
0

我建议使用该ToArray()方法(或仅使用List<string>ArrayList 的 instad)来利用OrderByandThenBy函数。它看起来像这样:

list = list.OrderBy(/*Order it by length*/).ThenBy(/*Order alphabetically*/);
于 2013-01-10T14:41:23.837 回答
0

您可以创建一个IComparable接收两个字符串的类,并按如下方式对它们进行排序:

if (a.Length == b.Length)
    return String.Compare(a, b);
return a.Length.CompareTo(b.Length);

您可能还想处理null案件。

于 2013-01-10T14:42:06.397 回答
0

这是一种老派,但是,我去了 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
于 2013-01-10T14:52:29.503 回答