Generics SortedList Question

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Sorts great!...but in only one direction.

We would like to have the list descending as well.
 
Sean said:
Sorts great!...but in only one direction.

We would like to have the list descending as well.

.... so write a different comparer, and pass that into the sort method.
Comparers are generally trivial to write (less than 10 lines of code,
usually more like 3 or 4), and overloaded sort functions can take them as
arguments.
 
Chris Mullins said:
... so write a different comparer, and pass that into the sort method.
Comparers are generally trivial to write (less than 10 lines of code,
usually more like 3 or 4), and overloaded sort functions can take them as
arguments.

The code looks like:

private void DoSomething()
{
List<string> foo = new List<string>();
foo.Add("a");
foo.Add("b");
foo.Add("z");
foo.Add("e");
foo.Add("j");
foo.Sort(new StringReverseComparer());
MessageBox.Show(foo[0]);
}

public class StringReverseComparer : IComparer<string>
{
public virtual int Compare(string x, string y)
{
return x.CompareTo(y) * -1;
}
}

The framework already has all the relevant comparers for the basic types, so
this isn't something you would normally do for a string collection, but the
point is valid for any generic type.
 
Thanks I will look more into that code you wrote.


Chris Mullins said:
Chris Mullins said:
... so write a different comparer, and pass that into the sort method.
Comparers are generally trivial to write (less than 10 lines of code,
usually more like 3 or 4), and overloaded sort functions can take them as
arguments.

The code looks like:

private void DoSomething()
{
List<string> foo = new List<string>();
foo.Add("a");
foo.Add("b");
foo.Add("z");
foo.Add("e");
foo.Add("j");
foo.Sort(new StringReverseComparer());
MessageBox.Show(foo[0]);
}

public class StringReverseComparer : IComparer<string>
{
public virtual int Compare(string x, string y)
{
return x.CompareTo(y) * -1;
}
}

The framework already has all the relevant comparers for the basic types, so
this isn't something you would normally do for a string collection, but the
point is valid for any generic type.
 
I wouldn't even bother to wate time in the multiplication (for -1). It
should be sufficient to reverse operands in the compare ;-)

-tom
 
Back
Top