0

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
Luis Lora
  • 83
  • 1
  • 9
  • The code you have highlighted is not your issue... I believe the issue is inside your foreach – austin wernli Jun 04 '15 at 22:43
  • How can I extract the First value and Second value inside foreach loop? That's what I want to know – Luis Lora Jun 04 '15 at 22:45
  • did you check what does result contain? – Angloos Jun 04 '15 at 22:46
  • There is nothing wrong with the code you have posted. There must be something wrong with the contents of the `foreach` loop. Post that and we can help you, until then I'm flagging this question as off-topic. – DavidG Jun 04 '15 at 22:52
  • This is my foreach `foreach (var item in result) { total = subtotal + Int32.Parse(item.ToString()) * 2; }` – Luis Lora Jun 04 '15 at 22:57
  • Put a break-point on the foreach statement and check what type/data result has. I'm pretty sure it cannot be converted directly to an integer, since you are selecting two columns. The result is probably an IEnumerable of a dictionary or something. – HaukurHaf Jun 04 '15 at 23:08

2 Answers2

1

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
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

you should try to

foreach (var item in result)
{
  total = subtotal + Int32.Parse(item.First) * 2
}
Yuri
  • 2,820
  • 4
  • 28
  • 40