Monday, May 18, 2009

Sorting in Generic List [c#]

It is very easy to sort generic list when it use 'string','int' etc.Just use it's inbuilt 'sort' function. But it is little bit tricky when an object[with multiple properties] use with generic list. An Object which has more that one properties than it is difficult to sort list by its inbuilt 'sort' function.Suppose a list with some items.

List<+ListItem+>ListValues = new List<+ListItem+>();

*Please remove '+' symbol from above line.

ListItem _item1 = new ListItem();
_item1.Text =”alex”;
_item1.Value =”1”;
ListValues.Add(_item1);

ListItem _item2 = new ListItem();
_item2.Text =”minto”;
_item2.Value =”2”;
ListValues.Add(_item2);

In this situation now we have two option for sorting.
Ø Sorting with Text
Ø Sorting with Value


For ‘Text’ sorting
ListValues.Sort(delegate(ListItem first, ListItem second) { return first.Text.CompareTo(second.Text); });

For ‘Value’ sorting
ListValues.Sort(delegate(ListItem first, ListItem second) { return first. Value.CompareTo(second.Value); });

No comments:

Post a Comment