1

I am using C#, .NET 4.7

I have 3 strings ie.

[test.1, test.10, test.2]

I need to sort them to get:

test.1
test.2
test.10

I may get other strings like

[1test, 10test, 2test]

which should produce:

1test
2test
10test

using same approach.

Thoughts?

Thanks in advance.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
SamJolly
  • 6,347
  • 13
  • 59
  • 125

3 Answers3

3

You could use Parse the number using Regex and then sort the string. For example,

Regex re = new Regex(@"\d+");
var result = strArray.Where(x=>re.Match(x).Success)
                .Select(x=> new { Key = int.Parse(re.Match(x).Value),Value = x})
                .OrderBy(x=>x.Key).Select(x=>x.Value);

Where strArray is the collection of strings.

Please note in the above case, you are ignoring string which doesn't have a numeric part (as it wasn't described in OP). The numeric part of string is parsed using Regex, which is then used for sorting the collection.

Example, Input

var strArray = new string[]{"1test", "10test", "2test"};

Output

1test 
2test 
10test 

Input

var strArray = new string[]{"test.1", "test.10", "test.2"};

Outpuyt

test.1 
test.2 
test.10 
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
2

For your first array you can do

var array = new[] { "test.1", "test.10", "test.2" };

var sortedArray = array.OrderBy(s => int.Parse(s.Substring(5, s.Length - 5)));

For the second array

var array = new[] { "1test", "2test", "10test" };

var sortedArray = array.OrderBy(s => int.Parse(s.Substring(0, s.Length - 4)));
DotNet Developer
  • 2,973
  • 1
  • 15
  • 24
1

Try this code. It uses SortedDictionary which always sort it's items by key when they are inserted.

  static void Main(string[] args)
        {
            SortedDictionary<int, string> tuples = new SortedDictionary<int, string>();
            string[] stringsToSortByNumbers = { "test.1", "test.10", "test.2" };

            foreach (var item in stringsToSortByNumbers)
            {
                int numeric = Convert.ToInt32(new String(item.Where(Char.IsDigit).ToArray()));
                tuples.Add(numeric, item);
            }

            foreach (var item in tuples)
            {
                Console.WriteLine(item.Value);
            }

            Console.ReadKey();

        }
MartinS
  • 751
  • 3
  • 12
  • 27