Sorting in C# In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.
You can use LINQ to create a new list which contains the original values but sorted: var sortedList = list. OrderBy(x => x). ToList();
One way to do this is with a delegate
List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });
You are correct that your cTag class must implement IComparable<T>
interface. Then you can just call Sort()
on your list.
To implement IComparable<T>
interface, you must implement CompareTo(T other)
method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public string date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public DateTime date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String)
method.
For this case you can also sort using LINQ:
week = week.OrderBy(w => DateTime.Parse(w.date)).ToList();
List<cTag> week = new List<cTag>();
week.Sort((x, y) =>
DateTime.ParseExact(x.date, "dd.MM.yyyy", CultureInfo.InvariantCulture).CompareTo(
DateTime.ParseExact(y.date, "dd.MM.yyyy", CultureInfo.InvariantCulture))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With