0

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.

1
  • This is a duplicate of This Question Commented Aug 4, 2011 at 7:45

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

no need to check for b - the compareTo should handle it if implemented correctly
Nope, because you are passing in b.Date so if b==null then you will get a NullReferenceException
0

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.