how to sort a collection by datetime in c#

C#Sorting

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

var query = 
    from m in mystuffcollection
    orderby m.Created ascending
    select m;

Solution 3 - C#

For those who are looking for a way to sort the data on the basis of a nested property can use the sort function something like below:

MyList.Sort((x, y) => x.Datetime.CompareTo(y.Datetime));

Now the major differences between using OrderBy and Sort are performance and return value.

Sort basically sorts the existing List<T> whereas OrderBy returns a new IEnumerable<T>

Solution 4 - C#

You can use using System.Linq; from entity framework, considering you are using .net core in your application. The Linq provides you both FilterBy and OrderBy methods, for custom FilterBy and OrderBy you need to override the methods in your class or Repository.

 override
 protected IQueryable<T> FilterBy(IQueryable<T> myProcess, string filterBy, string filterValue)
                {
                    var listFilter = filterBy.Split(',');
                    var listValues = filterValue.Split(',');
        
                    for (int index = 0; index < listFilter.Length; index++)
                    {
                        var filter = listFilter[index];
                        var value = listValues[index];
        
                        switch (filter)
                        {
                            case "type":
                                myProcess = myProcess.Where(c => c.Status.Nome.Contains(value));
                                break;
                            case "created":
                                  myProcess = myProcess.Where(c => c.Created - DateTime.Parse(value) >= new TimeSpan(0, 0, 0));
                            default:
                               break;
                  }
                }
              }
        
    override
    protected IQueryable<T> OrderBy(IQueryable<T> myProcess, string attribute, string direction)
                {
                    switch (attribute)
                    {
                        case "type":
                            myProcess = (direction == "asc")
                                ? myProcess.OrderBy(c => c.Type)
                                : myProcess.OrderByDescending(c => c.Type);
                            return myProcess;
                        case "created":
                            myProcess = (direction == "asc")
                                ? myProcess.OrderBy(c => c.Created)
                                : myProcess.OrderByDescending(c => c.Created);
                    return myProcess;
                 }
                }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser195968View Question on Stackoverflow
Solution 1 - C#NoldorinView Answer on Stackoverflow
Solution 2 - C#popesterView Answer on Stackoverflow
Solution 3 - C#FreakyAliView Answer on Stackoverflow
Solution 4 - C#Darleison RodriguesView Answer on Stackoverflow