I will show one way to reach it.
Sample:
class TopicCandidate: IComparable<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