[SOLVED] Switch statement inside enumeration. How to improve performance?


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 => {
      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?


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;

    case "conditionB":
        orderBy = i => (float)i.MemberB;

        orderBy = i => (int)i.MemberC;

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)

Leave a Reply

Your email address will not be published. Required fields are marked *