tags:

views:

68

answers:

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

+2  A: 

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
+2  A: 
var obj = myObjects.OrderBy(o => o.id).First();
danijels
A: 

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
+1  A: 

Use the First method.

For example:

var data = (from o in Orders
           order by o.OrderID
           select o.Name).First();
Branimir
A: 

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.

mumtaz
+1  A: 

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