use LINQ to find the product with the cheapest value?

前端 未结 3 1875
梦谈多话
梦谈多话 2021-01-13 15:27

Im learning LINQ and I want to find the cheapest product from the following list:

List products = new List { 
                n         


        
3条回答
  •  不知归路
    2021-01-13 16:12

    You should use MinBy:

    public static TSource MinBy(
        this IEnumerable source,
        Func 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;                
        }
    }
    

    Just add this as a method in a public static class (EnumerableExtensions?).

    Now you can say

    var cheapest = products.MinBy(x => x.Price);
    

提交回复
热议问题