2

in a for loop I receive results from a db as dynamic type

dynamic {system.collections.generic.List<object>}

I need to collect these results into one single variable.

I tried defining a variable

 dynamic results = new List<object>();

and then

 var queryResults = _dbManager.Query(query);
 results = results.Concat(queryResults);

but I have this exception:

 System.Collections.Generic.List<object> does non contain a definition for 'Concat'

I can't find a solution. Do you how can I do this? Thanks!

ctt_it
  • 339
  • 1
  • 6
  • 22
  • You have added `using System.Linq`? – Tim Schmelter Apr 13 '17 at 13:53
  • Yes, I did. System.Collections, System.Collections.Generic, System.Linq and some others. – ctt_it Apr 13 '17 at 13:54
  • Why does results need to be dynamic? If you're just looking for an enumerator bag then on all of your queries use .Cast().ToList() and you'll have a list of objects from which you can work with. Or...results needs to be an IEnumerable which will honor linq syntax. – BlackjacketMack Apr 13 '17 at 14:04

2 Answers2

7

The problem is that dynamic types and extension methods don't work well together (read the explanation of Eric Lippert on the why). You have to call the extension method yourself as a static method (which it actually is):

var l = Enumerable.Concat(results, queryResults);
Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

Concat is an extension method. Extension methods are a compiler syntactic sugar. Essentially the compiler chooses the appropriate static method to call based on the static type of the object on which you call the extension method. But dynamic variable have no static type so the compiler cannot search for extension methods.

Edit: Patrick Hofman's solution should work, but it is not LINQ that does not work well with extension methods. In fact LINQ is heavily relying on extension methods. The problem is LINQ assumes static typing of variable (and actually is the very reason to use LINQ: get the compiler validate your code for type safety)

P. Kouvarakis
  • 1,893
  • 12
  • 21
  • I guess you are partly in the right direction, however, if it is compile-time syntactic sugar, it would mean that it would give a compiler error, not a runtime error. There is more going on. – Patrick Hofman Apr 13 '17 at 13:57
  • It gives a runtime error because the compiler does not have enough type information to emit an extension method call. But since this is a dynamic type, it also does not check if the requested method is implemented by the type - it just emits a regular member method call and leaves it for the runtime when the actual type will be known to check whether the method actually exists. – P. Kouvarakis Apr 13 '17 at 14:01