Reputation: 137
I'm trying to sort a string array that contains numbers just by the letters so for example:
Original array = {"09Bananas", "Pears2", "Mangoes39Bad", "100Apples", "Mangoes38Good"}
Should become:
Sorted array = {"100Apples", "09Bananas", "Mangoes39Bad", "Mangoes38Good", "Pears2"}
However when I try to use Array.sort(original)
it would come out like this:
{"09Bananas", "100Apples", "Mangoes38Good", "Mangoes39Bad", "Pears2"}
Is there an overload of Array.sort
that would make it ignore numbers?
Thanks
Upvotes: 4
Views: 2560
Reputation: 460108
You could write a method that returns the string without digits and use that with Enumerable.OrderBy
:
private string TextOnly(String input)
{
StringBuilder sb = new StringBuilder();
foreach (Char c in input)
if (!Char.IsDigit(c))
sb.Append(c);
return sb.ToString();
}
use it:
var original = new[] { "09Bananas", "Pears2", "Mangoes39Bad", "100Apples", "Mangoes38Good" };
var ordered = original.OrderBy(s => TextOnly(s));
// if you need it as: String[] orderedArray = ordered.ToArray();
To order the original array instead, you can use Array<T>.Sort
as @dasblinkenlight has mentioned:
Array.Sort<String>(original, (s1, s2) => TextOnly(s1).CompareTo(TextOnly(s2)));
Upvotes: 3
Reputation: 726569
Use Array.Sort<T>(T[],IComparer<T>)
overload, and skip digits before comparing strings.
var array = new[] {
"09Bananas", "Pears2", "Mangoes39Bad", "100Apples", "Mangoes38Good"
};
Array.Sort(array, (a,b) => {
a = new string(a.Where(char.IsLetter).ToArray());
b = new string(b.Where(char.IsLetter).ToArray());
return a.CompareTo(b);
});
Console.WriteLine(string.Join(", ", array));
The LINQ expression a.Where(char.IsLetter).ToArray()
converts a string to an array of individual letters.
Upvotes: 6