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
views:
68answers:
6
+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
2010-09-30 19:10:32
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
2010-09-30 19:11:09
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
2010-09-30 20:09:06
+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
2010-09-30 20:09:39