从动态变量中的集合中获取项目

Mar*_*rko 6 c# ienumerable dynamic

我正在研究一些使用动态变量的代码.

dynamic variable;
Run Code Online (Sandbox Code Playgroud)

在场景后面,这个变量包含Shapes集合,它又是动态变量的集合.所以这样的代码工作正常:

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

我需要从这个系列中获得第一个项目高度.这个黑客很好用:

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

有没有更好的方法来实现这一目标?

Gre*_*Ros 7

因为variabledynamic,您将无法评估variable.Shapes.First(),因为扩展方法的确定在编译时发生,并且动态调用在运行时发生.您必须显式调用静态方法,

System.Linq.Enumerable.First<TType>(variable.Shapes).Height.TType可枚举项中预期的项目类型在哪里.

否则,使用其他人建议的LINQ.


dkn*_*ack 6

描述

您可以使用 LINQ方法First()FirstOrDefault()获取第一项。

First() -返回序列的第一个元素。

FirstOrDefault() -返回序列的第一个元素,如果序列不包含任何元素,则返回默认值。

样品

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;
}
Run Code Online (Sandbox Code Playgroud)

更多信息