在枚举中切换语句.如何提高性能?

Guy*_* L. 0 c# linq performance

我有一个项目列表,我想使用Linq OrderByDescending排序.排序作为值传递给switch语句.

items.OrderByDescending((SomeObject)i => {
   switch(cond)
   {
      case "conditionA":
        return (float)i.MemberA;
      case "conditionB":
        return (long)i.MemberB;
      case "conditionC":
        return (int)i.MemberB;
   }})
Run Code Online (Sandbox Code Playgroud)

我关心的是这个循环的性能.有没有办法预先定义返回值并将其传递给循环一次?

Ale*_*eev 5

您可以将开关移到外部OrderByDescending方法.只需将lambda定义为Func<SomeObject, float>并在linq查询之前分配它:

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;
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在排序中使用该lambda

var res = items.OrderByDescending(orderBy);
Run Code Online (Sandbox Code Playgroud)

如果items是,IQueriable你可以Func<...>改为Expression<Func<...>>