by Keyvan Nayyeri via Keyvan Nayyeri on 2/8/2007 8:24:53 PM
Today I was working on a short code to get some data (objects with different properties), add them to a list and bind a GridView to this list. Suddenly I noticed that data should be sorted based on one of properties before binding. This was the first time that I had to sort items in a list because I always had control on my data before getting them and was able to sort them from the original class but this time objects were coming out from somewhere outside my control.
The nice point was the simple solution that everyone knows or can find it in a moment. But for unknown reasons I love this code (probably because I like anonymous methods!).
Suppose that we have a class like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace SortLists
{
internal class Soldier
public Soldier(string Name, int Age)
this.name = Name;
this.age = Age;
}
private string name;
public string Name
get { return name; }
set { name = value; }
private int age;
public int Age
get { return age; }
set { age = value; }
And we have some object instances of this class and we need to sort these items based on their Age property before passing them along or displaying them somewhere.
There is a Sort() method for List<T> that does the job. Its usage is very simple. Just pass a delegate that gets two instances of this type and return a Comparer<T> of their comparison result.
static void Main(string[] args)
Console.Title = ":-D";
List<Soldier> soldiers = new List<Soldier>();
soldiers.Add(new Soldier("Keyvan Nayyeri", 22));
soldiers.Add(new Soldier("Gholi Javatzadeh", 30));
soldiers.Add(new Soldier("Javat Gholeidarzadeh", 20));
soldiers.Sort(delegate(Soldier soldier1, Soldier soldier2)
return Comparer<int>.Default.Compare
(soldier1.Age, soldier2.Age);
});
foreach (Soldier soldier in soldiers)
Console.WriteLine("Name: {0} - Age: {1}",
soldier.Name, soldier.Age.ToString());
Console.ReadLine();
How nice are these Generics!
+ Note to self (actually note to others because I always do this!): if you're creating a collection based type, please do a favor and provide some common operations for it. I bet, it's not so hard!
Original Post: Sort Items in a List
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.