根据Pro LINQ: Language Integrated Query in C# 2008,OrderBy运算符的原型是
public static IOrderedEnumerable<T> OrderBy<T, K>(
this IEnumerable<T> source,
Func<T, K> keySelector)
where
K : IComparable<K>
但是MSDN 文档对TKey没有泛型约束,它应该是类型IComparable<TKey>
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
我基本上是按Unit然后按Size对 Inventory 进行排序。
var sortedInventories = inventories
.OrderBy(inventory => inventory.Unit)
.OrderBy(inventory => inventory.Size);
从上面的代码片段中,lambda 表达式只是返回要排序的库存属性。它看起来不像返回的表达式IComparer<T>
但根据逻辑,看起来 lambda 表达式应该是 type IComparer<T>
。
哪个是正确的声明OrderBy
?
(Apress.com Errata 页面上没有任何信息)
这是我为测试而创建的示例应用程序OrderBy
public class Program
{
public static void Main(string[] args)
{
var inventories = new[] {
new Inventory { Unit = 1, Size = 2 },
new Inventory { Unit = 2, Size = 4 },
new Inventory { Unit = 3, Size = 6 },
};
var sortedInventories = inventories
.OrderBy(inventory => inventory.Unit)
.OrderBy(inventory => inventory.Size);
foreach (var inventory in sortedInventories)
Console.WriteLine("Unit: {0}; Size = {1}", inventory.Unit, inventory.Size);
}
}
public class Inventory
{
public int Unit { get; set; }
public double Size { get; set; }
}