paddy
paddy

Reputation: 165

sort array of strings by a part of these strings

I am attempting to sort xls lines by fourth string in lines.

string[] list_lines = System.IO.File.ReadAllLines(@"E:\VS\WriteLines.xls");



        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of Your Database = ");

        foreach (var line in list_lines)
        {

            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

I am having problems creating algorithm that will identify the fourth element of each line and list content in alphabetical order. The words in each line are separated by ' '.

Can anyone put me on a right direction please?

EDIT-------------------------- ok,

foreach (var line in list_lines.OrderBy(line => line.Split(' ')[3]))

sorted the problem. Lines are sorted as I need. Excel changes ' ' spaces with ';'. That's why when compiled it was giving error.

Now, I guess, I need to parse each part of string to int since it sorts by first digit and not by a number.

Upvotes: 1

Views: 404

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Well, just sort the array:

string[] list_lines = ...;

// General case: not all strings have 4 parts
Array.Sort(list_lines, (left, right) => {
  String[] partsLeft = left.Split(' ');
  String[] partsRight = right.Split(' ');

  if (partsLeft.Length < 4)
    if (partsRight.Length < 4)
      return String.Compare(left, right, StringComparison.OrdinalIgnoreCase) 
    else 
      return -1;
  else if (partsRight.Length < 4)
    return 1; 

  return String.Compare(partsLeft[3], partsRight[3], StringComparison.OrdinalIgnoreCase);
});

If all the lines guaranteed to have 4 items at least it can be simplfied into

Array.Sort(list_lines, (left, right) => 
  String.Compare(left.Split(' ')[3],
                 right.Split(' ')[3],
                 StringComparison.OrdinalIgnoreCase));

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156948

You can split the lines and then use the third item in an OrderBy:

foreach (var line in list_lines.OrderBy(line => line.Split(' ')[3]))
{
}

Upvotes: 1

Related Questions