Sorting List<String> in C#

Thorin Oakenshield picture Thorin Oakenshield · Sep 15, 2010 · Viewed 14k times · Source

How to sort a List based on the item's integer value

The list is like

"1"
"5"
"3"
"6"
"11"
"9"
"NUM1"
"NUM0"

The result should be like

"1"
"3"
"5"
"6"
"9"
"11"
"NUM0"
"NUM1"

is there any idea to do this using LINQ or Lambda expression?

Thanks in advance

Answer

Marc Gravell picture Marc Gravell · Sep 15, 2010

How about:

    list.Sort((x, y) =>
    {
        int ix, iy;
        return int.TryParse(x, out ix) && int.TryParse(y, out iy)
              ? ix.CompareTo(iy) : string.Compare(x, y);
    });