4

我正在学习 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));

你能告诉我实现这一目标的正确方法吗?

4

3 回答 3

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);
于 2012-06-06T10:59:54.280 回答
1

或者,您可以简单地订购它们并获取第一个结果,这是假设您在Product对象而不是Price值之后;像这样。

var cheapestProduct = products.OrderBy(p => p.Price).FirstOrDefault();
var mostExpensiveProduct = products.OrderByDescending(p => p.Price).FirstOrDefault();
于 2012-06-06T10:58:10.107 回答
0

您需要先按价格订购,然后选择第一个。

if(products.Any()){
    var productWithCheapestPrice = products.OrderBy(p => p.Price).First();
}
于 2012-06-06T10:59:18.047 回答