Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a string array alphabetically ignoring numbers and symbols

Tags:

string

c#

sorting

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

like image 388
quotidian Avatar asked Jan 17 '23 00:01

quotidian


1 Answers

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.

like image 74
Sergey Kalinichenko Avatar answered Jan 31 '23 11:01

Sergey Kalinichenko