C# switch in lambda expression

后端 未结 6 932
夕颜
夕颜 2021-02-04 04:04

Is it possible to have a switch in a lambda expression? If not, why? Resharper displays it as an error.

6条回答
  •  面向向阳花
    2021-02-04 04:49

    In a pure Expression (in .NET 3.5), the closest you can get is a compound conditional:

        Expression> func = x =>
            x == 1 ? "abc" : (
            x == 2 ? "def" : (
            x == 3 ? "ghi" :
                     "jkl")); /// yes, this is ugly as sin...
    

    Not fun, especially when it gets complex. If you mean a lamda expression with a statement body (only for use with LINQ-to-Objects), then anything is legal inside the braces:

        Func func = x => {
            switch (x){
                case 1:  return "abc";
                case 2:  return "def";
                case 3:  return "ghi";
                default: return "jkl";
            }
        };
    

    Of course, you might be able to outsource the work; for example, LINQ-to-SQL allows you to map a scalar UDF (at the database) to a method on the data-context (that isn't actually used) - for example:

    var qry = from cust in ctx.Customers
              select new {cust.Name, CustomerType = ctx.MapType(cust.TypeFlag) };
    

    where MapType is a UDF that does the work at the db server.

提交回复
热议问题