我正在学习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},
};
我已经提出以下内容,但不知何故感觉这不是最好的方法:
var cheapest = products.Find(p => p.Price == products.Min(m => m.Price));
你能告诉我正确的方法吗?
答案 0 :(得分: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;
}
}
只需将此作为方法添加到public static
班级(EnumerableExtensions
?)。
现在你可以说
var cheapest = products.MinBy(x => x.Price);
答案 1 :(得分:1)
或者,您可以简单地对它们进行排序并获取第一个结果,假设您在Product
对象之后而不是Price
值;像这样。
var cheapestProduct = products.OrderBy(p => p.Price).FirstOrDefault();
var mostExpensiveProduct = products.OrderByDescending(p => p.Price).FirstOrDefault();
答案 2 :(得分:0)
您需要先按价格订购,然后选择第一个。
if(products.Any()){
var productWithCheapestPrice = products.OrderBy(p => p.Price).First();
}