LINQ Min() and Max() optimisation

linq max min
linq where max
linq max date
linq group by max
linq sql max
linq max count
linq max value of column
linq group by max lambda

I'm having some trouble doing it right.

I need to pick the minimum and maximum for a list inside a list inside a list

Any thought how I can create a optimized type?

var range = allFilteredCars
            .SelectMany(car => car.LeasingPlans
                .SelectMany(plan => plan.Durations)
                .Select(a => a.MonthlyPrice))
            .ToList();

        var min = range.Min();
        var max = range.Max();

The last Min() and Max() doesn't feel right.

Any thoughts?

I don't think you can get around the multiple SelectManys but an Ordering in the query will get rid of the Min/Max. This should be quicker as you are then only sorting once:

var range = allFilteredCars
        .SelectMany(car => car.LeasingPlans
            .SelectMany(plan => plan.Durations)
            .Select(a => a.MonthlyPrice))
            .OrderBy(a => a))
        .ToList();

    var min = range[0]; // get the first
    var max = range[range.Count-1];  // get the last

Optimizing Sum, Count, Min, Max and Average with LINQ » DamienG, LINQ Min() and Max() optimisation, I don't think you can get around the multiple SelectMany s but an Ordering in the query will get rid of the Min/Max. This should​  Optimizing Sum, Count, Min, Max and Average with LINQ. 4 September 2014.NET Elasticsearch LINQ Entity Framework C#. LINQ is a great tool for C# programmers letting you use familiar syntax with a variety of back-end systems without having to learn another language or paradigm for many query operations.

I can think of only one way to calculate min and max just by iterating one time on the entire collection which can be done using foreach loop

var min = Int32.MaxValue;
var max = Int32.MinValue;
foreach(var filteredCard in allFilteredCars)
{
    foreach(var leasingPlan in filteredCard.LeasingPlans) 
    {
        foreach(var car in leasingPlan.Durations) 
        {
          if(car.MonthlyPrice < min)
            min = car.MonthlyPrice;
          else if(car.MonthlyPrice > max)
            max = car.MonthlyPrice;
        }
     }
}

Assuming MonthlyPrice is of Int

LINQ Min() and Max() optimisation, Max() select a_item' 2017-07-30 15:41:34.075 +02:00 [Warning] The LINQ expression 'Min()' could not be translated and will be evaluated  Min() and Max() methods Very simply, the Min() method returns the minimum value from the source sequence and the Max() method returns the maximum value. As with the Sum() method, they can only be called on sequences containing numerical values.

We will do a bad thing: a linq expression with a side effect.

int? min = null;
int? max = null;

allFilteredCars
    .SelectMany(car => car.LeasingPlans
        .SelectMany(plan => plan.Durations))
            .Select(a =>
            {
                if (min == null || a.MonthlyPrice < min.Value)
                {
                    min = a.MonthlyPrice;
                }

                if (max == null || a.MonthlyPrice > max.Value)
                {
                    max = a.MonthlyPrice;
                }

                return true;
            }).All(x => x);

In the end you don't really seem to need the range result... You only want the Min() and Max(), so we calculate it, and force the whole IEnumerable<> to be elaborated through the use of All().

You have to replace int? with the type of MonthlyPrice!

Optimizing entity framework linq queries – timdows, Extracting the minimum or maximum element of a list by a LINQ has very useful Max() and Min() methods that can be used to The only thing left to potentially optimised is that we are still calling keySelector() for a list of a  Max (LINQ) Enumerable.Max is extension method from System.Linq namespace. It returns maximal value of numeric collection. Max for Numeric Types. Gets maximal number from list of integer numbers.

LINQ Extensions 2: Minimum/Maximum by key – GameDev<T>, Min and Max are both extension methods with 22 overloads each. Unlike the optimizations and set ordering (where it's reasonably forgivable to deliberately Of course you'd have to call First() for non-nullable values and  The Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) method uses the Decimal implementation of IComparable<T> to compare values. You can apply this method to a sequence of arbitrary values if you provide a function, selector, that projects the members of source into a numeric type, specifically Decimal.

Reimplementing LINQ to Objects: Part 29 – Min/Max, In LINQ, you can find the maximum element of the given sequence by using Max​() function. This method provides the maximum element of the given set of  Min (LINQ) Enumerable.Min is extension method from System.Linq namespace. It returns minimal value of numeric collection. Min for Numeric Types. Gets minimal number from list of integer numbers.

LINQ, LINQ Min method usage examples. public struct Money : IComparable<Money​> { public Money(decimal value) : this() { Value = value; } public decimal Value  Min/Max optimization with GROUP BY MariaDB and MySQL support loose index scan, which can speed up certain GROUP BY queries. The basic idea is that when scanning a BTREE index (the most common index type for the MariaDB storage engines) we can jump over identical values for any prefix of a key and thus speed up the scan significantly.

Comments
  • I dunno, sorting is O(n lg(n)). Getting the first & last item can be done in O(n).
  • You don't need to sort to get the min() and max(). These can be found in a single pass.
  • Agree with other commenters - this is not the optimal way of doing things and is in fact worse than the original method once n is more than a handful of items.
  • My thoughts too. You go from iterating the list twice to iterating it once.
  • This is indeed the optimal solution (the second if can even become else if since value cannot be both less than min and greater than max). LINQ has no way to calculate multiple aggregates in a single pass (except Aggregate, which basically is ugly foreach).