Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Max and Min in a single LINQ query

Tags:

c#

linq

I have a set of objects with two properties, A and B. I'd like to get the Min of A and the Max of B.

eg

var minA = objects.Min(o => o.A);
var maxB = objects.Max(o => o.B);

Using LINQ query syntax, is there a way to do this so it only passes over the set once?

Desired outcome would be an anonymous type (eg, results.MinA = x, results.MaxB = y)

like image 350
cyrus Avatar asked Mar 07 '14 02:03

cyrus


People also ask

How do you find the maximum value in LINQ?

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 values.

How do you find the minimum value in LINQ?

In LINQ, you can find the minimum element of the given sequence by using Min() function. This method provides the minimum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

Min and Max are both aggregates. The general linq aggregate function is Aggregate

Assuming property A is an integer, and B is a string, you could write something like this:

objects.Aggregate(
    new {
        MinA = int.MaxValue,
        MaxB = string.Empty
    },
    (accumulator, o) => new {
        MinA = Math.Min(o.A, accumulator.MinA),
        MaxB = o.B > accumulator.MaxB ? o.B : accumulator.MaxB
    });
like image 80
Cirdec Avatar answered Sep 19 '22 13:09

Cirdec