Joe Smith
Joe Smith

Reputation: 139

Sort List<String[]>

How do you sort a List alphanumerically by the value in string[0]?

Upvotes: 5

Views: 3719

Answers (2)

Doug Chamberlain
Doug Chamberlain

Reputation: 11341

This is a terribly oversimplified/pseudo code example... Really stretching here...

MyclassZeroIndexComparer : IComparable, IList(Of String[])
{
  private List<String[]> listOfStringArrays;

  //expose this as a public member somewhere...
  private List<String[]> listofStringArrayZeroIndex; 

  //internally store a list of only the first item you want to index....
  //implement your own, add,remove,clear

  void Add(foo item)
  {
    listofStringArrays.Add(Item);
    listofStringArrayZeroIndex.add(item[0]); 
  }

  // continue implementing other methods in the same manner.
}

Upvotes: -1

jason
jason

Reputation: 241583

Try

list.Sort((s, t) => String.Compare(s[0], t[0]));

This will sort lexicographically by the first element of each array in list.

Since I don't know exactly what you mean by "alphanumerically", if you need a custom string comparing routing, you should do this:

class MyStringComparer : IComparer<string> {
    public int Compare(string s, string t) {
        // details elided
    }
}

and then

var comparer = new MyStringComparer();
list.Sort((s, t) => comparer.Compare(s[0], t[0]));

Upvotes: 14

Related Questions