Issue
I have a list of items that I would like to sort using Linq OrderByDescending.
The sorting is being passed as value to a switch statement.
items.OrderByDescending((SomeObject)i => {
switch(cond)
{
case "conditionA":
return (float)i.MemberA;
case "conditionB":
return (long)i.MemberB;
case "conditionC":
return (int)i.MemberB;
}})
My concern is regarding the performance of this loop.
Is there a way to pre-define the return value and to pass it into the loop once?
Solution
You can move your switch outside OrderByDescending
method. Just define a lambda as Func<SomeObject, float>
and assign it before linq query:
Func<SomeObject, float> orderBy = null;
switch (cond)
{
case "conditionA":
orderBy = i => (float)i.MemberA;
break;
case "conditionB":
orderBy = i => (float)i.MemberB;
break;
default:
orderBy = i => (int)i.MemberC;
break;
}
Now you can use that lambda in your sorting
var res = items.OrderByDescending(orderBy);
If items
is an IQueryable
you can change Func<...>
to Expression<Func<...>>
Answered By – Aleks Andreev
Answer Checked By – Clifford M. (BugsFixing Volunteer)