by Adam
12. November 2010 17:33
Creating a collection can save a lot of time and provide a useful way to store a lot of information. But what happens when you want to sort an IEnumerable? Well after a little bit of coding it's possible to create a class that can do this for you and a solution which is both simple and easily reused.
I came across the problem after creating a class which has a number of elements. I then wanted to create a list of this class so I extended IENumerable. Then I noticed that it was not possible to sort this list by a specific element.
I've created a basic sample below to show the solution I used for this.
First, lets set up a basic class and a collection to set the ground for this sample.
public class Person
{
private string _name;
private int _age;
public string Name {
get { return _name; }
set { _name = value; }
}
public int Age {
get { return _age; }
set { _age= value; }
}
public DeskOrder(string name, int age) {
_name = name;
_age = age;
}
}
Next a list of those classes
public class PersonList : IEnumerable<Person>
{
public PersonList()
{ }
public List<Person> rows = new List<Person>();
IEnumerator<Person> IEnumerable<Person>.GetEnumerator() {
return rows.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return rows.GetEnumerator();
}
public Person this[int index] {
get { return rows[index]; }
}
public virtual void Add(Person person) {
rows.Add(person);
}
public Person Get(int index) {
return rows[index];
}
}
Next, create the sort class. This is the part you want.
class SortField
{
public enum sortOrderEnum {
Descending = 0,
Ascending = 1
}
private sortOrderEnum order;
private string name;
public string Name {
get { return name; }
set { name = value; }
}
public sortOrderEnum Order {
get { return order; }
set { order = value; }
}
public SortField(string NameValue, sortOrderEnum OrderValue) {
Name = NameValue;
Order = OrderValue;
}
}
And that's it! Anytime you want to sort the list of classes you can do it by using the code below...
PersonList personList = new PersonList()
//.... add some people to the list.....
List<SortField> sortFields = new List<SortField>();
sortFields.Add(new SortField("Name", SortField.sortOrderEnum.Ascending));
sortFields.Add(new SortField("Age", SortField.sortOrderEnum.Descending));
personList.rows.Sort(new GenericComparer<Person>(sortFields));