开发者

Using an Anonymous method to populate a property in an object initializer

开发者 https://www.devze.com 2022-12-10 05:52 出处:网络
Assuming sr is an IEnumerable<string>, I want to use code like this to do an inline calculation using two of the items from sr.Lines().The problem is that the lambda is of type\"lambda expressio

Assuming sr is an IEnumerable<string>, I want to use code like this to do an inline calculation using two of the items from sr.Lines(). The problem is that the lambda is of type "lambda expression" and not a Decimal, which shares is expecting. Is there any way to do this type of inline method in an object initializer?

var trades =
 from line in sr.Lines()
 let items = line.Split('|')
 select new Trade
       {
       开发者_开发百科  Total = () => { 
           return Convert.ToDecimal(items[1]) + Convert.ToDecimal(items[2]);
         },
         Name = items[3]
       }


You want a decimal expression, not a function:

var trades =
 from line in sr.Lines()
 let items = line.Split('|')
 select new Trade
       {
         Total = Convert.ToDecimal(items[1]) + Convert.ToDecimal(items[2]),
         Name = items[3]
       };


Just in case someone else ends up here looking for a solution like I did.

Check How to call anonymous function in C#?.

var trades =
from line in sr.Lines()
let items = line.Split('|')
select new Trade
   {
     Total = ((Func<decimal>)(() =>
     {
         return Convert.ToDecimal(items[1]) + Convert.ToDecimal(items[2]);
     }))(),
     Name = items[3]
   };
0

精彩评论

暂无评论...
验证码 换一张
取 消