Sorting a Text File or ArrayList Based on Multiple Columns

I’ve been working with huge text files lately. One of the many small tasks I need to perform is to sort delimited text files by more than one field. For example, suppose a file looks like:
And suppose you want to sort by last name and then by first name. If the file is small enough to read into memory, you can read everything into an array, a List<>, or an ArrayList of Person objects, then call a built-in Sort() method with a custom IComparer along the line of:
public class Person
  public string lastName;
  public string firstName;
  public int age;
  public Person(string ln, string fn, int a)
    lastName = ln; firstName = fn; age = a;
  public override string ToString()
    return lastName + “ “ firstName + “ “ + age;
  public class myComparer : IComparer // by last name then first
    int IComparer.Compare(object x, object y)
      Person p1 = (Person)x;
      Person p2 = (Person)y;
      string lastname1 = p1.lastName;
      string lastname2 = p2.lastName;
      int lastNameCompare = lastname1.CompareTo(lastname2);
      if (lastNameCompare != 0) // if last names not equal
        return lastNameCompare; // we’re done
      else // compare by first name
        string firstname1 = p1.firstName;
        string firstname2 = p2.firstName;
        return firstname1.CompareTo(firstname2);
  } // class myComparer
} // class Person
Now if you have an ArrayList loaded with Person objects (presumably loaded from a file), you can sort them with:
theArrayList.Sort(new Person.myComparer());
Now you can produce a sorted file by writing the contents of the sorted ArrayList out to a text file.
This entry was posted in Software Test Automation. Bookmark the permalink.