开发者

Sorting an object list

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 t开发者_如何转开发hat makes this sort easy?

Thanks.


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().


You can implement IComparer<YourObject> and use that comparer for sorting


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜