Retrieving an item from a collection in a dynamic variable

I am working on some code that uses dynamic variables.

dynamic variable; 

Behind the scenes, this variable contains the Shapes collection, which again is a collection of dynamic variables. So code like this works fine:

 foreach(var shape in variable.Shapes) //Shapes is dynamic type too { double height = shape.Height; } 

I need to get the first height of an element from this collection. This hack works well:

 double height = 0; foreach(var shape in variable.Shapes) { height = shape.Height; //shape is dynamic type too break; } 

Is there a better way to do this?

+4
source share
2 answers

Since variable is dynamic , you will not be able to evaluate variable.Shapes.First() , since the definition of extension methods happens at compile time, and the dynamic call happens at runtime. You will have to call the static method explicitly,

System.Linq.Enumerable.First<TType>(variable.Shapes).Height . Where TType is the expected type of elements in the enumerated.

Otherwise use LINQ as others suggested.

+5
source

Description

You can use the LINQ First() or FirstOrDefault() method to get the first item.

First () - returns the first element of the sequence.

FirstOrDefault () . Returns the first element of a sequence or the default value if the sequence contains no elements.

Example

 using System.Linq; double height = 0; // this will throw a exception if your list is empty var item = System.Linq.Enumerable.First(variable.Shapes); height = item.Height; // in case your list is empty, the item is null and no exception will be thrown var item = System.Linq.Enumerable.FirstOrDefault(variable.Shapes); if (item != null) { height = item.Height; } 

Additional Information

+4
source

Source: https://habr.com/ru/post/1435155/


All Articles