Never been to DZone Snippets before?

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

Sort generic list (See related posts)

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 on this post

nico posts on Jul 20, 2007 at 07:31
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)

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts