Reputation: 2026
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();
If i run this program, i will get the below result
But i want to sort the list like Item1,Item2,Item3,Item4,Item5,Item6,Item7,Item8,Item9,Item10,Item11
Upvotes: 1
Views: 1296
Reputation: 460288
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)))
);
Upvotes: 0
Reputation: 2590
The result is sorted that way because it uses lexicographic ordering on the strings. The comparison algorithm compares two strings from left to right, and since "1"
is less than "9"
, "10"
will be less than "9"
, too.
You could pad the numeric parts of your strings with zeroes, e.g. "Item05"
instead of "Item5"
.
The more generic and flexible way is to use ArrayList.Sort(IComparer)
, and implement an IComparer
that understands your string format and can order the strings correctly.
Upvotes: 1
Reputation: 447
You can implement a IComparer
and pass it to the Sort
method.
http://msdn.microsoft.com/en-us/library/0e743hdt.aspx
Upvotes: 0
Reputation: 75326
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
Upvotes: 4
Reputation: 873
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.
Upvotes: 0