【问题标题】:Sorting a list of objects对对象列表进行排序
【发布时间】:2013-04-26 04:12:30
【问题描述】:

我正在尝试根据实例化对象的类中的方法(称为 Q())的返回值对对象列表进行排序。 Decaf 和Regular 两个类都派生自同一个类Coffee。这两个派生类也具有所讨论方法 Q() 的不同实现。它看起来像这样:

static void Main(string[] args)
{
      Decaf decafCoffee = null;
      Regular regularCoffee = null;
      List<Coffee> inventory = new List<Coffee>();
      if (type.StartsWith("D:"))
      {
          // The value of M changes based on certain criteria
          decafCoffee = new Decaf(name, D, C, M);
          inventory.Add(decafCoffee);
      }
      else if (type.StartsWith("R:"))
      {
          regularCoffee = new Regular(name, D, C, M);
          inventory.Add(regularCoffee);
      }   

      for (int j = 0; j < inventory.Count; j++)
      {
          Console.WriteLine("{0}", inventory[j].toString());
      }         
}

如何按两个类中方法 Q() 的值按升序对这个列表进行排序?如果需要,我可以发布课程代码。

【问题讨论】:

    标签: c# list sorting object


    【解决方案1】:

    最简单的方法大概是使用Linq的OrderBy方法:

    var sorted = inventory.OrderBy(i => i.Q());
    

    这将返回一个IEnumerable——如果你想要一个List,只需这样做:

    var sortedList = inventory.OrderBy(i => i.Q()).ToList();
    

    【讨论】:

    • 比 IComparable 快得多!
    • 远没有 IComparable 可怕!
    【解决方案2】:

    在两个类中实现 IComparable 接口并使用 .Sort 方法。

    这是一个例子。 http://www.codeproject.com/Articles/42839/Sorting-Lists-using-IComparable-and-IComparer-Inte

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多