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?
Asked
Active
Viewed 53 times
-4
-
1Did you search before asking? "Order list by attribute" should give you plenty of examples. – MakePeaceGreatAgain Sep 25 '19 at 08:45
-
2It would be awesome if you could share a [mcve]. – mjwills Sep 25 '19 at 08:46
2 Answers
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
-
-
https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – xdtTransform Sep 25 '19 at 09:10
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
-
1implementing `IComparable` (or `IComparable
`) is *one way* to solve this; by no means the only; `List – Marc Gravell Sep 25 '19 at 08:55` 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" -
@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