views:

36

answers:

1

Assuming sr is an IEnumerable, 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]
       }
+4  A: 

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]
       };
Yann Schwartz
I should have been more specific, I just used that as a small, readable example of what I wanted to do. The reality is that I might have relatively complex logic to calculate each of those fields with if or case statements, etc.
Dan
Then just wrap your complex logic in separate methods and call them in the initialization. Or if it's too long, don't use object initialization syntax at all.
Yann Schwartz
So your answer is, no, there is no way to do this? I have to use the object initializer syntax since it's part of a linq query. I'm aware that I could wrap it in a function, but I was trying to figure out if there was some sort of inline anonymous method way of doing it.
Dan