Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

sorting - how to sort a collection by datetime in c#

I have a List that I need to sort by DateTime, the class MyStuff looks like:

public class MyStuff
{
   public int Type {get;set;}
   public int Key {get;set;}
   public DateTime Created {get;set;}
}

I need to be able to sort the collection List by the Created (DateTime) field.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You seem to be working with a List<T> object, in which case the most efficient (and a simple) method would be the following:

myList.Sort((x, y) => DateTime.Compare(x.Created, y.Created));

This uses the overload of the List.Sort method than takes a Comparison<T> delegate (and thus lambda expression).

You can of course use the LINQ OrderBy extension method, but I don't think this offers any advantages, and can be significantly slower, depending on your situation.

myList = myList.OrderBy(x => x.Created).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...