Foreach Dynamic Linq Multiple Columns

c# dynamic-linq linq

Question

Hello I'm using dynamic linq and I have query like this one:

var result = DataContext.Table
    .Where("Code == @0", CodeId)
    .Select("new(SGL AS First, DBL AS Second)");

How can I loop the result?

I'm using something like this code but it doesn't work:

foreach (var item in result)
{
    total = subtotal + Int32.Parse(item.ToString()) * 2
}

It returns the following error:

The input string does not have the correct format.

1
0
6/4/2015 11:03:58 PM

Accepted Answer

The problem is in your foreach loop, not with the dynamic linq. This line:

total = subtotal + Int32.Parse(item.ToString()) * 2

Is going to convert your object to a string, which will look something like this:

{First=XXX, Second=YYY}

And if you pass that directly to Int32.Parse you will get the error you describe.

Instead you want to work on the properties of the object. One way is to cast the object to a dynamic value, then you can get the properties as you would any other object:

dynamic obj = resultItem;
total = subtotal + Int32.Parse(obj.First) * 2
1
6/4/2015 11:07:50 PM

Popular Answer

you should try to

foreach (var item in result)
{
  total = subtotal + Int32.Parse(item.First) * 2
}


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow