How to numerically sort an array of delimited strings in C #

I am a bit attached. I am working with an outdated system that contains a bunch of delimited strings that I need to parse. Unfortunately, strings need to be ordered based on the first part of the string. The array looks something like this:

array[0] = "10|JohnSmith|82";
array[1] = "1|MaryJane|62";
array[2] = "3|TomJones|77";

So, I would like the array to look like

array[0] = "1|MaryJane|62";
array[1] = "3|TomJones|77";
array[2] = "10|JohnSmith|82";

I was thinking of making a 2-dimensional array in order to capture the first part and leave the string in the second part, but can I mix types in a two-dimensional array?

I'm not sure how to handle this situation, can anyone help? Thanks!

+5
source share
5 answers

Call Array.Sortbut pass in custom implementation IComparer<string>:

// Give it a proper name really :)
public class IndexComparer : IComparer<string>
{
    public int Compare(string first, string second)
    {
        // I'll leave you to decide what to do if the format is wrong
        int firstIndex = GetIndex(first);
        int secondIndex = GetIndex(second);
        return firstIndex.CompareTo(secondIndex);
    }

    private static int GetIndex(string text)
    {
        int pipeIndex = text.IndexOf('|');
        return int.Parse(text.Substring(0, pipeIndex));
    }
}

, , . , , , .

, - - , ?

+13
        new[] {
            "10|JohnSmith|82",
            "1|MaryJane|62",
            "3|TomJones|77",
        }.OrderBy(x => int.Parse(x.Split('|')[0]));
+6

, , . IMO, , , . .

- :

class Person {
  int Index { get; }
  string Name { get; }
  int Age { get; }  // just guessing the semantic meaning
}

, :

  • Match your encoded string with ArrayListobjects Person.
  • Then use ArrayList.Sort(IComparer)where your comparator looks only at the index.

This is likely to be better than using parsing in each comparison.

+1
source

for lolz

Array.Sort(array, ((x,y) => (int.Parse(x.Split('|')[0]) < int.Parse(y.Split('|')[0])) ? -1 : (int.Parse(x.Split('|')[0]) > int.Parse(y.Split('|')[0])) ? 1 : 0));
0
source

All Articles