开发者

LINQ Order By to select lowest Index

开发者 https://www.devze.com 2023-01-18 02:12 出处:网络
I am relatively new to LINQ and don\'t know开发者_如何学JAVA 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 b

I am relatively new to LINQ and don't know开发者_如何学JAVA 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


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.


var obj = myObjects.OrderBy(o => o.id).First();


Use the First method.

For example:

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


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


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;


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消