C#如何在不手动实现IComparable的情况下对列表进行排序?

JL.*_*JL. 7 c#

我有一个相当复杂的场景,我需要确保列表中的项目已经排序.

首先,列表中的项目基于包含子结构的结构.

例如:

public struct topLevelItem
{
 public custStruct subLevelItem;
}

public struct custStruct
{
  public string DeliveryTime;
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个由topLevelItems组成的列表,例如:

var items = new List<topLevelItem>();
Run Code Online (Sandbox Code Playgroud)

我需要一种方法来对DeliveryTime ASC进行排序.还增加了复杂性的是DeliveryTime字段是一个字符串.由于这些结构是可重用API的一部分,因此我无法将该字段修改为DateTime,也无法在topLevelItem类中实现IComparable.

有什么想法可以做到这一点?

谢谢

Jus*_*ner 7

创建一个实现IComparer的新类型,并使用它的实例来比较对象.

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

然后你可以像这样调用Sort():

var items = new List<topLevelItem>();
// Fill the List
items.Sort(new topLevelItemComparer());
Run Code Online (Sandbox Code Playgroud)


LBu*_*kin 6

听起来你需要获得规范化的日期排序,即使你的日期表示为字符串,是吗?好吧,您可以使用LINQ的OrderBy运算符,但您必须将字符串解析为日期以获得正确的结果:

items = items.OrderBy(item => DateTime.Parse(item.subLevelItem.DeliveryTime))
             .ToList(); 
Run Code Online (Sandbox Code Playgroud)

更新:

为了完整性,我添加了这个 - 这是我如何将ParseExact与Invariant文化一起使用的一个真实示例:

var returnMessagesSorted = returnMessages.OrderBy((item => DateTime.ParseExact(item.EnvelopeInfo.DeliveryTime, ISDSFunctions.GetSolutionDateTimeFormat(), CultureInfo.InvariantCulture)));
return returnMessagesSorted.ToList();
Run Code Online (Sandbox Code Playgroud)

你总是可以实现一个单独的IComparer类,它并不好玩,但效果很好:

public class TopLevelItemComparer : IComparer<topLevelItem>
{
  public int Compare( topLevelItem x, topLevelItem y )
  {
      return DateTime.Parse(x.subLevelItem.DeliveryTime).CompareTo(
             DateTime.Parse(y.subLevelItem.DeliveryTime) );
  }
}

items.Sort( new TopLevelItemComparer() );
Run Code Online (Sandbox Code Playgroud)

请注意,Sort().NET框架中的大多数方法都接受IComparerIComparer<T>允许您重新定义任何类型的比较语义.通常情况下,您只需使用Comparer<T>.Default- 或使用基本上为您提供此功能的过载.