I have a fairly complex scenario and I need to ensure items I have in a list are sorted.
Firstly the items in the list are based on a struct that contains a sub struct.
For example:
public struct topLevelItem
{
public custStruct subLevelItem;
}
public struct custStruct
{
public string DeliveryTime;
}
Now I have a list comprised of topLevelItems for example:
var items = new List<topLevelItem>();
I need a way to sort on the DeliveryTime ASC. What also adds to the complexity is that the DeliveryTime field is a string. Since these structs are part of a reusable API, I can’t modify that field to a DateTime, neither can I implement IComparable in the topLevelItem class.
Any ideas how this can be done?
Thank you
It sounds like you need to get canonicalized date sorting even though your date is represented as a string, yes? Well, you can use LINQ’s
OrderByoperator, but you will have to parse the string into a date to achieve correct results:Update:
I’ve added this in for completeness – a real example of how I use ParseExact with Invariant culture:
You can always implement a separate IComparer class, it’s not fun, but it works well:
Be aware that most
Sort()methods in the .NET framework accept anIComparerorIComparer<T>which allows you to redefine the comparison semantics for any type. Normally, you just useComparer<T>.Default– or use an overload that essentially supplies this for you.