Tuesday, February 19, 2013

[C#] List Sort with Two Keywords

In C#, there is a collection List you can use to put in any kind of data type in it. Of course, all the items in it are with the same data type. Here is my topic: How to sort a list<T> where T is an user defined class and with two or more keywords?
I will show one way to reach it.
Sample:

  class TopicCandidateIComparable<TopicCandidate>
  {
   public string topic;
   public int length;
   public int weight;
   public TopicCandidate(string t, int l, int w)
   {
    this.topic = t;
    this.length = l;
    this.weight = w;
   }
   #region IComparable<Employee> Members
   public int CompareTo(TopicCandidate other) 
   {
    if (this.length == other.length)
     return this.weight.CompareTo(other.weight);
    else
     return this.length.CompareTo(other.length);
    
   }
   #endregion
  }

This is a class defined by me. I would like to sort list<TopicCandidate> cand order by fist length, and second weight. Then I can implement the interface IComparable to my class and implement the method Comparable(..) in my class. In this way, I can sort my list cand by just call the Sort() method of List, like cand.Sort(). It is ok.

Sure, there are other ways to sort a list<T>, like lamada expression and LINQ. After I learnt them, I will add them to this blog.

ps. Thanks this article from which I learnt this way. That is a very clear and readable article about List sort.

No comments:

Post a Comment