我正在尝试根据实例化对象的类中的方法的返回值(称为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()的值对此列表进行排序?如果需要,我可以发布类代码。
答案 0 :(得分:3)
最简单的方法可能是使用Linq的OrderBy
方法:
var sorted = inventory.OrderBy(i => i.Q());
这将返回IEnumerable
- 如果您想要List
,请执行以下操作:
var sortedList = inventory.OrderBy(i => i.Q()).ToList();
答案 1 :(得分:0)
在两个类中实现IComparable接口并使用.Sort方法。
这是一个例子。 http://www.codeproject.com/Articles/42839/Sorting-Lists-using-IComparable-and-IComparer-Inte