Search code examples
c#listlinq

Can I sort a List<string> by integers inside of them?


For example;

List<string> list = new List<string>{
"1[EMPTY]",  "2[EMPTY]",  "3[EMPTY]",  "4[EMPTY]",  "5[EMPTY]",  "6[EMPTY]",  "7[EMPTY]",  "8[EMPTY]",  "9[EMPTY]",  "10[EMPTY]",  "11[EMPTY]",  "12[EMPTY]"
};

When I use

list.Sort();

Output:

1[EMPTY] 10[EMPTY] 11[EMPTY] 12[EMPTY] 2[EMPTY] 3[EMPTY] 4[EMPTY] 5[EMPTY] 6[EMPTY] 7[EMPTY] 8[EMPTY] 9[EMPTY]

I want 1-2-3-4-5-6-7-8-9-10-11-12. How can i solve this problem?

(Sorry my English is bad :{)


Solution

  • You can use OrderBy. Basically trick is to sort the string so parsing as int. and getting the value till the first occurance of [.

            List<string> list = new List<string>{
    "1[EMPTY]",  "2[EMPTY]",  "3[EMPTY]",  "4[EMPTY]",  "5[EMPTY]",  "6[EMPTY]",  "7[EMPTY]",  "8[EMPTY]",  "9[EMPTY]",  "10[EMPTY]",  "11[EMPTY]",  "12[EMPTY]"
    };
                list = list.OrderBy(c => int.Parse(c.Substring(0, c.IndexOf('[')))).ToList();