我正在学习LINQ,我想从以下列表中找到最便宜的产品:
List<Product> products = new List<Product> {
new Product {Name = "Kayak", Price = 275M, ID=1},
new Product {Name = "Lifejacket", Price = 48.95M, ID=2},
new Product {Name = "Soccer ball", Price = 19.50M, ID=3},
};
Run Code Online (Sandbox Code Playgroud)
我想出了以下内容,但不知何故感觉它不是最好的方法:
var cheapest = products.Find(p => p.Price == products.Min(m => m.Price));
Run Code Online (Sandbox Code Playgroud)
你能告诉我实现这个目标的正确方法吗?
jas*_*son 10
你应该使用MinBy:
public static TSource MinBy<TSource>(
this IEnumerable<TSource> source,
Func<TSource, IComparable> projectionToComparable
) {
using (var e = source.GetEnumerator()) {
if (!e.MoveNext()) {
throw new InvalidOperationException("Sequence is empty.");
}
TSource min = e.Current;
IComparable minProjection = projectionToComparable(e.Current);
while (e.MoveNext()) {
IComparable currentProjection = projectionToComparable(e.Current);
if (currentProjection.CompareTo(minProjection) < 0) {
min = e.Current;
minProjection = currentProjection;
}
}
return min;
}
}
Run Code Online (Sandbox Code Playgroud)
只需将其添加为public static类(EnumerableExtensions?)中的方法即可.
现在你可以说
var cheapest = products.MinBy(x => x.Price);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2527 次 |
| 最近记录: |