CodeCloudy

Azure | .Net | JQuery | Javascript | Umbraco

Sort a list of strings numerically using LINQ

Lets take a case where you need to sort an array of numbers that are strings.

And the list need be sorted numerically.

One thing to note is that this is useful where you cannot convert them to int list.

 
typical way:
yourStringList.OrderBy(x => x.yourSortAttribute)
this will not sort it numerically. because they are strings.

so you need to give a comparer called SemiNumericComparer.
yourStringList.OrderBy(x => x.yourSortAttribute, new SemiNumericComparer())
 
Your have write a custom IComparer<T> class to overcome this issue. Add this class to you class library:

/// <summary>
/// Semi Numeric Comparer
/// </summary>
public class SemiNumericComparer : IComparer<string>
{
/// <summary>
/// Compares the specified s1.
/// </summary>
/// <param name=”s1″>The s1.</param>
/// <param name=”s2″>The s2.</param>
/// <returns>the specified s1.</returns>
public int Compare(string s1, string s2)
{
if (Convert.ToInt32(s1, CultureInfo.InvariantCulture) > Convert.ToInt32(s2, CultureInfo.InvariantCulture))
{
return 1;
}

if (Convert.ToInt32(s1, CultureInfo.InvariantCulture) < Convert.ToInt32(s2, CultureInfo.InvariantCulture))
{
return -1;
}

if (Convert.ToInt32(s1, CultureInfo.InvariantCulture) == Convert.ToInt32(s2, CultureInfo.InvariantCulture))
{
return 0;
}

return string.Compare(s1, s2, true, CultureInfo.InvariantCulture);
}
}

this should work now. Cheers! :)
for more information about the IComparer: http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx
Leave a comment »