Home
Manage Your Code
Snippet: Sort list of custom objects (C#)
Title: Sort list of custom objects Language: C#
Description: How to sort a list of custom objects Views: 3456
Author: - - Date Added: 5/22/2008
Copy Code  
1    public abstract class MyObject: IComparable<MyObject>
2    {       
3        public Int64 sortnumber { get; set; }
4
5        /// <summary>
6        /// Compare two objects
7        /// </summary>
8        /// <param name="other">The objects to be compared with.</param>
9        /// <returns>
10        /// A 32-Bit Signed Integer that states the relative sortorder of the two objects
11        /// </returns>
12        public int CompareTo(MyObject other)
13        {
14            return this.sortnumber.CompareTo(other.sortnumber);
15        }
16    }
Usage
List list = new List;
list.add(new MyObject() { sortnumber = 3 });
list.add(new MyObject() { sortnumber = 1 });
list.add(new MyObject() { sortnumber = 2 });
list.Sort(); // will sort the list for the sortnumber