Accepted answer

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


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


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


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(); = 12;

    test v2 = new test(); = 12;

    test v3 = new test(); = 12;

    list<test> arr = new list<test>();

    test max = arr.orderbydescending(t =>;

class test
    public int id { get; set; }


in nhibernate (with nhibernate.linq) you could do it as follows:

return session.query<t>()
              .single(a => a.filter == filter &&
                  == session.query<t>()
                                          .where(a2 => a2.filter == filter)
                                          .max(a2 =>;

which will generate sql like follows:

select *
from tablename foo
where foo.filter = 'filter on string'
and = (select cast(max(bar.rowversion) as int)
              from tablename bar
              where = 'filter on string')

which seems pretty efficient to me.


the answers so far are great! but i see a need for a solution with the following constraints:

  1. plain, concise linq;
  2. o(n) complexity;
  3. 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 => 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 => new tuple<t, r>(t, evaluate(t)))
        .aggregate((max, next) => next.item2.compareto(max.item2) < 0 ? next : max).item1;


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


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 ?


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);


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);

Related Query

More Query from same tag