1
ArrayList SortItems = new ArrayList();
        SortItems.Add("Item1");
        SortItems.Add("Item2");
        SortItems.Add("Item3");
        SortItems.Add("Item4");
        SortItems.Add("Item5");
        SortItems.Add("Item6");
        SortItems.Add("Item7");
        SortItems.Add("Item8");
        SortItems.Add("Item9");
        SortItems.Add("Item10");
        SortItems.Add("Item11");

        SortItems.Sort();

如果我运行这个程序,我会得到以下结果

在此处输入图像描述

但我想对列表进行排序,如Item1,Item2,Item3,Item4,Item5,Item6,Item7,Item8,Item9,Item10,Item11

4

5 回答 5

4

Build custom comparer:

public class CusComparer: IComparer
{
    public int Compare(object x, object y)
    {
        return int.Parse((x as string).Substring(4)) - int.Parse((y as string).Substring(4));
    }
}

So you can use:

ArrayList SortItems = new ArrayList();
SortItems.Add("Item1");
SortItems.Add("Item2");
SortItems.Add("Item3");
SortItems.Add("Item4");
SortItems.Add("Item5");
SortItems.Add("Item6");
SortItems.Add("Item7");
SortItems.Add("Item8");
SortItems.Add("Item9");
SortItems.Add("Item10");
SortItems.Add("Item11");

SortItems.Sort(new CusComparer());

But instead of using ArrayList, you should consider using List<T> with stronger type

于 2012-10-30T09:17:49.120 回答
1

结果以这种方式排序,因为它对字符串使用字典顺序。比较算法从左到右比较两个字符串,因为"1"小于"9",所以"10"也会小于"9"

您可以用零填充字符串的数字部分,例如,"Item05"而不是"Item5".

更通用和灵活的方法是使用ArrayList.Sort(IComparer),并实现一个IComparer理解您的字符串格式并可以正确排序字符串的方法。

于 2012-10-30T09:20:19.847 回答
0

Your question does not show what kind of result it is giving.

Use SortedList. As and when you add new item, it would be sorted. http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx Downside would be, you cannot have a repetition in the inputs.

于 2012-10-30T09:16:33.730 回答
0

If it's always prepended with "Item", you can split both and order by the numic part.

Note that i'll use a strongly typed List<String> instead:

List<String> SortItems = list.Select(s => new
                              {
                                  Item = s, 
                                  Number = int.Parse(s.Substring("Item".Length))
                              }).OrderBy(x => x.Number)
                              .Select(x => x.Item).ToList();

or you can use this Sort method overload to sort the original list directly:

list.Sort((a, b) =>  
    int.Parse(a.Substring("Item".Length)).CompareTo(int.Parse(b.Substring("Item".Length)))
);
于 2012-10-30T09:17:38.463 回答
0

您可以实现 aIComparer并将其传递给Sort方法。

http://msdn.microsoft.com/en-us/library/0e743hdt.aspx

于 2012-10-30T09:19:19.080 回答