How to use LINQ to select object with minimum or maximum property value
People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <
curMin.DateOfBirth ? x : curMin))
How to perform .Max() on a property of all objects in a collection and return the object with maximum value
We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.
In your case you'd do something like:
var item = items.MaxBy(x => x.Height);
This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy
):
- It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
- The ordering solution is O(n log n)
- Taking the
Max
value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion. - It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element
How can I use LINQ to get the instance with the highest value of a property in a child list?
You can select the count of each item in SecondClass and use Max
to find the maximum value. Then you select this value of each item in FirstClass and use Max
again:
int highestCount = input.Select(x => x.SecondClass.Select(y => y.Count).Max()).Max();
If you want to find the item with the highest count, you can replace the first Select by OrderByDescending and the second Max by FirstOrDefault:
var itemWithHighestCount = input.OrderByDescending(x => x.SecondClass.Select(y => y.Count).Max()).FirstOrDefault();
Online demo: https://dotnetfiddle.net/0rWARC
Better way to return an object by max() in LINQ
One liner
var item = Users.OrderByDescending(x => x.MonthlyWage).FirstOrDefault();
if(item != null)
Console.WriteLine("{0}: {1} {2} MAX", item.ID, item.Name, item.MonthlyWage);
Console.ReadLine();
If we want all top earners:
var wageGroups = from u in Users
group u by u.MonthlyWage into ug
orderby ug.Key descending
select new { MonthlyWage = ug.Key, Users = ug.ToList() };
var topEarners = wageGroups.First().Users;
foreach (var item in topEarners)
{
Console.WriteLine("{0}: {1} {2} MAX", item.ID, item.Name, item.MonthlyWage);
}
Console.ReadLine();
How can I get LINQ to return the index of the object which has the max value in a collection?
Well, if you wanted to, you could of course write an IndexOfMaxBy
extension yourself.
Example(untested):
public static int IndexOfMaxBy<TSource, TProjected>
(this IEnumerable<TSource> source,
Func<TSource, TProjected> selector,
IComparer<TProjected> comparer = null
)
{
//null-checks here
using (var erator = source.GetEnumerator())
{
if (!erator.MoveNext())
throw new InvalidOperationException("Sequence is empty.");
if (comparer == null)
comparer = Comparer<TProjected>.Default;
int index = 0, maxIndex = 0;
var maxProjection = selector(erator.Current);
while (erator.MoveNext())
{
index++;
var projectedItem = selector(erator.Current);
if (comparer.Compare(projectedItem, maxProjection) > 0)
{
maxIndex = index;
maxProjection = projectedItem;
}
}
return maxIndex;
}
}
Usage:
var indexOfPointWithHighestItem2 = myList.IndexOfMaxBy(x => x.Item2);
C# Using LINQ to filter each Object with Max Value in List of Objects
You can achieve the desired result at once with a simple GroupBy
and subsequent ordering within each group:
var highestByTitle = list
.GroupBy(t => t.title)
.Select(g => g.OrderByDescending(t => t.val).First())
.ToList();
Demo.
How to get the max value of a function in a list of objects (C#) ? -Beginner-
You need to use maximumArea
to store the max of the list, not the max of the current pair.
Trapezoid maximumArea = new Square(0); //Smallest possible trapezoid
foreach (Trapezoid t in Shape)
{
if (t.Area() > maximumArea.Area()) maximumArea = t;
}
Console.WriteLine(maximumArea);
You can also shorten this considerably using LINQ:
var maximumArea = shape.OrderByDescending( x => x.Area() ).First();
And if there's a chance that some trapezoids will tie, maybe you should get a list:
var max = shape.Max( x => x.Area() );
var maximumAreas = shape.Where( x => x.Area() == max).ToList();
LINQ: Getting the row with the maximum value of a given attribute
One alternative would be to use:
rows.Select(x => x.OrderByDescending(y => y.StatusDate).First());
... and check that the query optimiser knows that it doesn't really need to sort everything. (This would be disastrous in LINQ to Objects, but you could use MaxBy
from MoreLINQ in that case :)
(Apologies for previous version - I hadn't fully comprehended the grouping bit.)
Related Topics
How Does Hashset Compare Elements for Equality
How to Pass Constructor Parameters to Unity's Resolve() Method
Why New Fb API 2.4 Returns Null Email on MVC 5 with Identity and Oauth 2
What's the Difference Between System.Type and System.Runtimetype in C#
How to Set Up a Web API Controller for Multipart/Form-Data
Difference Between Namespace in C# and Package in Java
Does Java Have Something Similar to C# Properties
How to Read a .Net Guid into a Java Uuid
What Is the "Volatile" Keyword Used For
How to Lock a Table on Read, Using Entity Framework
How to Use the Cancellationtoken Property
Specified Argument Was Out of the Range of Valid Values. Parameter Name: Site
Passing a Vector/Array from Unmanaged C++ to C#
Sending Email with Attachments from C#, Attachments Arrive as Part 1.2 in Thunderbird