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]
};
精彩评论