0

I have string with numbers:

string s1 = "cos555cos";
string s2 = "coscos1";
string s3 = "22coscos";
string s4 = "333coscos";
string s5 = "cosco444s";

I made a list:

IList<string> test = new List<string>();
test.Add(s1);
test.Add(s2);
test.Add(s3);
test.Add(s4);
test.Add(s5);

How to order it by number. The result should be like:

s2, s3, s4, s5, s1

foreach (var item in test)
{
    Console.WriteLine(item);
}
4est
  • 3,010
  • 6
  • 41
  • 63

2 Answers2

2
    string s1 = "cos555cos";
    string s2 = "coscos1";
    string s3 = "22coscos";
    string s4 = "333coscos";
    string s5 = "cosco444s";


    IList<string> test = new List<string>();
    test.Add(s1);
    test.Add(s2);
    test.Add(s3);
    test.Add(s4);
    test.Add(s5);


    var orderedEnumerable = test.OrderBy(StripNumeric);

    foreach (string s in orderedEnumerable)
    {
        Console.WriteLine(s);
    }


    int StripNumeric(string input)
    {
        Regex digitsOnly = new Regex(@"[^\d]");
        return int.Parse(digitsOnly.Replace(input, ""));
    }
Matt Evans
  • 7,113
  • 7
  • 32
  • 64
0

order it by convert to int the matches of this regex:

\d+

something like:

Regex r = new Regex(@"\d+");
IList<string> test2 = new List<string>();
foreach(var item in test)
{
    Match match = r.match(item);
    test2.Add(match[0]);
}
Sort(test2);