LCJ
LCJ

Reputation: 22652

String List Sort based on Integer order

I have List. This list holds integer values only though the data type is string. I want to sort the list based on integer order of the items.

How do I achieve it?

List<string> newZipCodesList = new List<string>();

Upvotes: 1

Views: 2705

Answers (6)

user807566
user807566

Reputation: 2866

If it is safe to assume that all elements in the list are the same length (e.g. zip codes are typically 5 characters), then there is no need to call Int.Parse() or Convert.ToInt() on every single item before sorting. Even though they are represented as strings, the "alphabetic" sorting should still put them in numerical order, because "0" comes before "1" comes before "2" ... And would be faster than performing all the conversions.

In that case, this would work:

List<String> zipCodes = new List<String>();
zipCodes.Add("00124");
zipCodes.Add("00123");
zipCodes.Add("98765");
zipCodes.Add("12345");
zipCodes.Add("33333");
zipCodes.Add("24680");

// zipCodes = zipCodes.Select(z => z.PadLeft(5, '0')).ToList();
zipCodes.Sort();

for(int i = 0; i < zipCodes.Count; i++)
   Console.WriteLine(zipCodes[i]);

And here is the output:

00123
00124
12345
24680
33333
98765

If they are not the same length, you may be able to pad them, depending on how you are using the list later. (See commented line in code). This would convert things like 1 into 00001

Upvotes: 2

Haris Hasan
Haris Hasan

Reputation: 30097

You can use IComparer Interface to implement your own sort. You will have to create a class which will implement IComparer of T where T in this case would be string.

   newZipCodesList.Sort(new Test());

   public class Test : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            //return 1 when first is greater than second
            if(Convert.ToInt32(x) > Convert.ToInt32(y))
                return 1;
            //return -1 when first is less than second
            else if (Convert.ToInt32(x) < Convert.ToInt32(y))
                return -1;
            //return 0 if they are equal
            else
                return 0;
        }
    }

Upvotes: 2

Jalal Said
Jalal Said

Reputation: 16162

I don't know why you are using List<string> in the first place, but anyway you can either copy the list to int list, sort it then copy back to string, or sort the string by casting each comparer to int the compare it, or you can use API to sort strings with numerics values, but here you can use it for only numeric:

[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int StrCmpLogicalW(String x, String y);

so:

newZipCodesList.Sort(StrCmpLogicalW);

//Test:

List<string> list = new List<string>(new string[] { "1", "4", "17", "5", "112", "0" });

list.Sort(StrCmpLogicalW);

//results: 0, 1, 4, 5, 17, 112

Upvotes: 2

Sani Huttunen
Sani Huttunen

Reputation: 24385

The other answers can be used if the strings are all numbers. If that is not the case then have a look here for more complex sorting.

Upvotes: 0

SiN
SiN

Reputation: 3754

This is if you need to order by Integer.

List<string> sortedZipCodes = (from code in newZipCodesList
                               orderby Convert.ToInt32(code)
                               select code).ToList();

Upvotes: 2

Bob Vale
Bob Vale

Reputation: 18474

newZipCodesList.Sort( (a,b) => { 
                             int a1;
                             int a2;
                             if !(int.TryParse(a,out a1)) return 1;
                             if !(int.TryParse(b,out b1)) return -1;
                             return a1.CompareTo(b1);

}

Upvotes: 0

Related Questions