简体   繁体   中英

Assigning function invocation to anonymous field in c#

I am returning anonymous type from my linq query:

select new {
Exists = true,
Code = new Func<string,string>((string param) => {
                                      if (param == "T")
                                          return "Tab";
                                      if (param == "E")
                                          return "Eub";
                                      if (param == "C")
                                          return "GTW";
                                      if (param == "X")
                                          return "XUX";
                                      return "";
}
}

An error:

A lambda expression with a statement body cannot be converted to an expression tree

is being thrown but it does not tell me anything.

Question: How to handle that without creating new nonanonymous function?

Why use Func<string,string> ?

something.Select(x => new {
Exists = true,
Code = x.param == "T" ? "Tab" :
       x.param == "E" ? "Eub" :
       x.param == "C" ? "GTW" :
       x.param == "X" ? "XUX" : ""
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM