6

I am relatively new to LINQ and don't know how to do an Order By. I have an IEnumerable list of myObject and want to do something like select first myObject from myObjectList order by myObject.id asc How can I accomplish this? Thanks

MikeTWebb
  • 9,149
  • 25
  • 93
  • 132
  • 1
    Could you clarify this please? Do you *actually* need the ordered results, or just the result with the lowest ID? Do you need the *index* of that entry, or just the ID? – Jon Skeet Sep 30 '10 at 19:10
  • 1
    If you only need the result with the lowest ID, there is an implementation of a MinBy extension method [here](http://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value). It was written by some fella' I've never heard of though (his name is Jon Skeet, or something like that), so I dunno how much I trust it. – Chris Shouts Sep 30 '10 at 20:22
  • @Jon...some clarity. I need the object in the list that has the lowest Id. – MikeTWebb Oct 01 '10 at 19:20

7 Answers7

7

Ascending is the default order by direction.

var query = from myObject in myObjectList
            orderby myObject.id
            select myObject;

Object o = query.FirstOrDefault();

If you want descending, you will want to use orderby myObject.id descending.

villecoder
  • 13,323
  • 2
  • 33
  • 52
3
var obj = myObjects.OrderBy(o => o.id).First();
danijels
  • 5,211
  • 4
  • 26
  • 36
2

Use the First method.

For example:

var data = (from o in Orders
           order by o.OrderID
           select o.Name).First();
Branimir
  • 4,327
  • 1
  • 21
  • 33
1

If you want the item with the lowest ID, you don't need an OrderBy... It is much faster to just enumerate the list once, since this operation has O(n) complexity whereas a typical sort has O(n log n) complexity. You can do it with a foreach loop, or use an extension method like this one:

    public static T WithMin<T, TValue>(this IEnumerable<T> source, Func<T, TValue> selector)
    {
        var min = default(TValue);
        var withMin = default(T);
        bool first = true;
        foreach (var item in source)
        {
            var value = selector(item);
            int compare = Comparer<TValue>.Default.Compare(value, min);

            if (compare < 0 || first)
            {
                min = value;
                withMin = item;
            }
            first = false;
        }
        return withMin;
    }

Use it like that:

var objectWithMinId = myObjectList.WithMin(o => o.Id);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • what if the backing store (e.g. SQL) has an index and LINQ can take advantage of that? enumerating the full set is akin to a full table scan. – magma Jul 08 '15 at 00:50
  • @magma, yes, but in this case it was pretty clear that the backing store was an in-memory collection, so I wrote my answer with that in mind. If the backing store is a database, you're better off doing an OrderBy and take the first item. – Thomas Levesque Jul 08 '15 at 08:07
  • in-memory that's a great tip! – magma Jul 09 '15 at 00:09
0

I would prefer using FirstOrDefault() in place of First() , in case your query does not return any elements then First() will throw a Exception.

var myObj = (from myObject in myObjectList orderby myObject.id select myObject).FirstOrDefault();
Rohit Jindal
  • 679
  • 1
  • 10
  • 21
0

Ascending is the default if you wanted the reverse just use OrderByDescending()

var obj = myObjectList.OrderBy(x => x.id).First();

if you needed the ID or some other property from the object you can keep the same line

int myID = myObjectList.OrderBy(x => x.id).First().id;
Bobby Borszich
  • 11,639
  • 9
  • 37
  • 35
0

Your query should look like following:

var yourquery = (from myObject in myObjectList
                 orderby myObject.id
                 select myObject).First();

Now the variable yourquery contains the object you require.

explorer
  • 11,710
  • 5
  • 32
  • 39