Marko
Marko

Reputation: 1924

Getting item from collection in dynamic variable

I'm working on some code which uses dynamic variables.

dynamic variable;

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

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

I need to get first item height 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 better way to accomplish this?

Upvotes: 8

Views: 8253

Answers (2)

GregRos
GregRos

Reputation: 9103

Because variable is dynamic, you won't be able to evaluate variable.Shapes.First(), since determination of extension methods occurs at compile time, and dynamic invocation occurs 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 the items in the enumerable.

Otherwise, use LINQ as others have suggested.

Upvotes: 8

dknaack
dknaack

Reputation: 60448

Description

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

First() - Returns the first element of a sequence.

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

Sample

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;
}

More Information

Upvotes: 8

Related Questions