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)
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.
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#.
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With