Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to sort a list without implementing IComparable manually?

Tags:

c#

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

like image 726
JL. Avatar asked May 05 '10 13:05

JL.


1 Answers

Create a new type that implements IComparer and use an instance of it to compare the objects.

public class topLevelItemComparer : IComparer<topLevelItem>
{
    public int Compare(topLevelItem a, topLevelItem b)
    {
        // Compare and return here.
    }
}

You can then call Sort() like this:

var items = new List<topLevelItem>();
// Fill the List
items.Sort(new topLevelItemComparer());
like image 140
Justin Niessner Avatar answered Sep 28 '22 21:09

Justin Niessner