DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Sort Generic List

06.07.2007
| 18555 views |
  • submit to reddit
        
public class Item
{
 public Item(string term, int freq)
 {
  _term = term;
  _freq = freq;
 }

 private string _term;
 public string Term
 {
  get { return _term; }
  set { _term = value; }
 }

  private int _freq;
  public int Freq
  {
   get { return _freq; }
   set { _freq = value; }
  }
 }

 public class ItemComparer:IComparer<Item>
 {
  #region IComparer<Item> Members

  public int Compare(Item x, Item y)
  {
   return y.Freq - x.Freq; //descending sort
   //return x.Freq - y.Freq; //ascending sort
  }

  #endregion
 }

static void Main()
{
 List<Item> items = new List<Item>();
 ....
 items.Sort(new ItemComparer());
}

    

Comments

Snippets Manager replied on Fri, 2007/05/25 - 4:57am

you could also use: items.Sort(delegate(Item x, Item y) {return x.Freq - y.Freq;} ); you can also refer to lokal variable: int orderMode = -1; // 1 asc, -1 desc items.Sort(delegate(Item x, Item y) {return (x.Freq - y.Freq)*orderMode;} ); (normaly you would make orderMode an enum)