Reputation: 372
I am keeping a list of objects in a List()
. I want to sort this list by a property of the object.
For example, say the object is a Messsage and message has: content, date, header, ...
I want to sort the list by the message's date.
Is there any List
method or any other method that makes this sort easy?
Thanks.
Upvotes: 0
Views: 92
Reputation: 18474
If you are using generics (ie using List) you can use the Sort method MSDN
See my answer ot this question for out to create an extension method that lets you do
myList.SortBy(x=>x.Date)
Upvotes: 0
Reputation: 93080
Yeah, use sort. If your list is l:
l.Sort((a,b) => {
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
return a.Date.CompareTo(b.Date)
});
This assumes that the date property is of type that implements CompareTo().
Upvotes: 2
Reputation: 30127
You can implement IComparer<YourObject>
and use that comparer for sorting
Upvotes: 0