score:320
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
score:1
based on cameron's initial answer, here is what i've just added at my enhanced version of silverflow library's floatingwindowhost (copying from floatingwindowhost.cs at http://clipflair.codeplex.com source code)
public int maxzindex
{
get {
return floatingwindows.aggregate(-1, (maxzindex, window) => {
int w = canvas.getzindex(window);
return (w > maxzindex) ? w : maxzindex;
});
}
}
private void settopmost(uielement element)
{
if (element == null)
throw new argumentnullexception("element");
canvas.setzindex(element, maxzindex + 1);
}
worth noting regarding the code above that canvas.zindex is an attached property available for uielements in various containers, not just used when being hosted in a canvas (see controlling rendering order (zorder) in silverlight without using the canvas control). guess one could even make a settopmost and setbottommost static extension method for uielement easily by adapting this code.
score:1
you can also upgrade mehrdad afshari's solution by rewriting the extention method to faster (and better looking) one:
static class enumerableextensions
{
public static t maxelement<t, r>(this ienumerable<t> container, func<t, r> valuingfoo) where r : icomparable
{
var enumerator = container.getenumerator();
if (!enumerator.movenext())
throw new argumentexception("container is empty!");
var maxelem = enumerator.current;
var maxval = valuingfoo(maxelem);
while (enumerator.movenext())
{
var currval = valuingfoo(enumerator.current);
if (currval.compareto(maxval) > 0)
{
maxval = currval;
maxelem = enumerator.current;
}
}
return maxelem;
}
}
and then just use it:
var maxobject = list.maxelement(item => item.height);
that name will be clear to people using c++ (because there is std::max_element in there).
score:2
i believe that sorting by the column you want to get the max of and then grabbing the first should work. however, if there are multiple objects with the same max value, only one will be grabbed:
private void test()
{
test v1 = new test();
v1.id = 12;
test v2 = new test();
v2.id = 12;
test v3 = new test();
v3.id = 12;
list<test> arr = new list<test>();
arr.add(v1);
arr.add(v2);
arr.add(v3);
test max = arr.orderbydescending(t => t.id).first();
}
class test
{
public int id { get; set; }
}
score:2
in nhibernate (with nhibernate.linq) you could do it as follows:
return session.query<t>()
.single(a => a.filter == filter &&
a.id == session.query<t>()
.where(a2 => a2.filter == filter)
.max(a2 => a2.id));
which will generate sql like follows:
select *
from tablename foo
where foo.filter = 'filter on string'
and foo.id = (select cast(max(bar.rowversion) as int)
from tablename bar
where bar.name = 'filter on string')
which seems pretty efficient to me.
score:35
the answers so far are great! but i see a need for a solution with the following constraints:
- plain, concise linq;
- o(n) complexity;
- do not evaluate the property more than once per element.
here it is:
public static t maxby<t, r>(this ienumerable<t> en, func<t, r> evaluate) where r : icomparable<r> {
return en.select(t => new tuple<t, r>(t, evaluate(t)))
.aggregate((max, next) => next.item2.compareto(max.item2) > 0 ? next : max).item1;
}
public static t minby<t, r>(this ienumerable<t> en, func<t, r> evaluate) where r : icomparable<r> {
return en.select(t => new tuple<t, r>(t, evaluate(t)))
.aggregate((max, next) => next.item2.compareto(max.item2) < 0 ? next : max).item1;
}
usage:
ienumerable<tuple<string, int>> list = new[] {
new tuple<string, int>("other", 2),
new tuple<string, int>("max", 4),
new tuple<string, int>("min", 1),
new tuple<string, int>("other", 3),
};
tuple<string, int> min = list.minby(x => x.item2); // "min", 1
tuple<string, int> max = list.maxby(x => x.item2); // "max", 4
score:40
and why don't you try with this ??? :
var itemsmax = items.where(x => x.height == items.max(y => y.height));
or more optimise :
var itemmaxheight = items.max(y => y.height);
var itemsmax = items.where(x => x.height == itemmaxheight);
mmm ?
score:170
doing an ordering and then selecting the first item is wasting a lot of time ordering the items after the first one. you don't care about the order of those.
instead you can use the aggregate function to select the best item based on what you're looking for.
var maxheight = dimensions
.aggregate((agg, next) =>
next.height > agg.height ? next : agg);
var maxheightandwidth = dimensions
.aggregate((agg, next) =>
next.height >= agg.height && next.width >= agg.width ? next: agg);
score:230
this would require a sort (o(n log n)) but is very simple and flexible. another advantage is being able to use it with linq to sql:
var maxobject = list.orderbydescending(item => item.height).first();
note that this has the advantage of enumerating the list
sequence just once. while it might not matter if list
is a list<t>
that doesn't change in the meantime, it could matter for arbitrary ienumerable<t>
objects. nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). however, it's still a less than ideal solution for large sequences. i suggest writing your own maxobject
extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (o(n)):
static class enumerableextensions {
public static t maxobject<t,u>(this ienumerable<t> source, func<t,u> selector)
where u : icomparable<u> {
if (source == null) throw new argumentnullexception("source");
bool first = true;
t maxobj = default(t);
u maxkey = default(u);
foreach (var item in source) {
if (first) {
maxobj = item;
maxkey = selector(maxobj);
first = false;
} else {
u currentkey = selector(item);
if (currentkey.compareto(maxkey) > 0) {
maxkey = currentkey;
maxobj = item;
}
}
}
if (first) throw new invalidoperationexception("sequence is empty.");
return maxobj;
}
}
and use it with:
var maxobject = list.maxobject(item => item.height);
Source: stackoverflow.com
Related Query
- How to perform .Max() on a property of all objects in a collection and return the object with maximum value
- How to query the average from a certain property in an Entity and return it in a List of List of objects in LINQ?
- How to sum a field for all records and then return the max of all summed records with Linq
- How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?
- How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n
- How to check if all of the elements in a list return true for a property using Linq?
- How to select all the values of an object's property on a list of typed objects in .Net with C#
- How to determine if all objects inside List<T> has the same property value using Linq
- If I have a collection of classes how can I return a collection of a single attribute of all the classes?
- How can I return a object with the sum of all objects from a list using Linq?
- How do I group items from a collection using LINQ and return the shaped data according the collection type
- How to fill properties of objects using LINQ and return collection
- How to hit a url from controller in MVC 5 and get the return data from that url to perform some task
- LINQ: How to join on only a single row with the MAX ID of the join column, and not all rows?
- How do I return all of the child objects - I can't get SelectMany to work
- Get the max value of a property in a collection or return zero when the sequence is empty
- How to match string in 2 diff collection and return the collection items that did not match in LINQ
- How do I return all items in a collection that possess an interface property of a specific type?
- How to execute a linq query for each item in a list , use it in the where clause and return a collection from the result of each query?
- Use Linq to return all objects in a list where the object's sub-object-list property contains all values of an int list
- How do I group by two fields and return the original objects that match?
- How to make LINQ to EF and LINQ to ordinary collection return the same values?
- Searching each property value of an IQueryable collection of T against the value of a search query. How do I test for NOT NULL and CONTAINS together?
- How can I get LINQ to return the object which has the max value for a given property?
- How can I filter a dictionary using LINQ and return it to a dictionary from the same type
- How to count the number of code lines in a C# solution, without comments and empty lines, and other redundant stuff, etc?
- How do I get the latest date from a collection of objects using LINQ?
- How to insert a record with LINQ and C# and return the Primary Key of that record
- How to make a linq Sum return null if the summed values are all null
- LINQy way to check if any objects in a collection have the same property value
More Query from same tag
- Linq equivalent to SQL LIKE [a-f]
- Poor performance comparing collections of objects using reflections and Linq Except/Intersect
- C# Linq Where(expression).FirstorDefault() vs .FirstOrDefault(expression)
- Quickest way to learn Linq to Entities
- Do I have to close the SQL Connection manually if I use Linq?
- How to get a List<TypeOf> objects, from this XML?
- InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expression
- Using LINQ in C#, How to retrieve list of events based on specific dates, for example all events that are planned for upcoming 45 days?
- Getting values from JSON objects using LINQ
- How to efficiently group all implementations by interface from multiple assemblies?
- Handling and calculate the formula saved in the database
- Dynamic property + Linq
- Validating Membership.GeneratePassword
- Getting Random File from Directory Tree
- How do I get summ in Linq query?
- How to populate a view models using a linq query ASP.NET MVC 5 Entity Framework
- Trying to convert linq Query to IQueryable
- Refactoring near identical linq queries where the where clause is different
- Find items not in datatable that are present in List<customclass>
- LINQ to XML query returning a list of all child elements
- Determine if foreign key table has any links to primary key table with LINQ & DataTable
- Linq simple query returns unexpected results
- Confused on Updating Table using DataGrid
- Write function that return data to datagridView in Entity Framework
- IList with an implicit sort order
- Get details by joining tables with group by condition in Linq and EF
- IQueryable order by two or more properties
- Finding Sum in LINQ
- Merging two Arrays using LinQ
- intersect two lists with different objects