CodeCloudy

Azure | .Net | JQuery | Javascript | Umbraco

Sort a list of strings numerically using LINQ

on May 17, 2012

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: