-4

Im trying to figure out, how to sort a List in C# by one value. Each entry of the list has a name, a date time and a second number. How can i sort that by the date time?

mjwills
  • 23,389
  • 6
  • 40
  • 63

2 Answers2

1
var sortedList = initialList.OrderBy(item => item.DateTimeField).ToList();

p.s: use OrderBy or OrderByDescending depending on what order type you want(asc/desc)

Cata Hotea
  • 1,811
  • 1
  • 9
  • 19
0

I assume the list contains elements of a custom class? In that case your class should implement IComparable.

Example

class MyClass : IComparable
{
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }
    public int Number { get; set; }

    // Constructor
    public MyClass()
    {
    }

    public int CompareTo(object obj)
    {
        if (obj is DateTime otherTimestamp)
        {
            return this.Timestamp.CompareTo(otherTimestamp);
        }

        return 0;  // If obj  is not a DateTime or is null, return 0
    }
}
Stefan
  • 652
  • 5
  • 19
  • 1
    implementing `IComparable` (or `IComparable`) is *one way* to solve this; by no means the only; `List` has a `Sort` method that accepts ad-hoc comparers, for example, or there's all of LINQ to play with; neither of which makes your type do something just because you want it sorted in a particular way in *one place*. It only makes sense to implement `IComparable[]` if that is a **natural and obvious** unambiguous semantic meaning to "sort these items" – Marc Gravell Sep 25 '19 at 08:55
  • @MarcGravell Good comment. I just wanted to show _one_ way of achieving his goal. Not sure it is the right one. He will decide for himself. – Stefan Sep 25 '19 at 08:59
  • https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – xdtTransform Sep 25 '19 at 09:11