【发布时间】:2009-03-29 21:53:49
【问题描述】:
根据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 documentation 对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);
从上面的代码 sn-p 中,lambda 表达式只是返回要排序的库存属性。它看起来不像返回IComparer<T>的表达式
但根据逻辑,看起来 lambda 表达式应该是 IComparer<T> 类型。
OrderBy 的正确声明是哪一个?
(Apress.com Errata page 没有相关信息)
这是我为测试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; }
}
【问题讨论】: