[英]How to declare dynamic array in c#
我正在研究silverligth5
(我以前的经验是c ++),我必须创建一个动态数组,其大小是动态决定的。
直到我一切都变得静态,这是这样的:
string[] position = new string[20]; //it must be dynamic I don't want to fix it to 20
for (int i = 0; i < pv.Root.Parameter.Count; i++)
{
if (name == pv.Root.Parameter[i].Name)
{
position[i] = name;
}
}
可以看出,我的方式将仅具有大小20
并且我希望它的长度仅与pv.Root.Parameter.Count
相同。
如何实现呢?
编辑/当我尝试通过列表实现问题时:在此行出现问题:
if (pv.Root.Parameter[loopCount].Name == position[loopCount])
{
rowGrid.Opacity=0.3;
}
因为肯定是因为position是一个List并且不能像这样被索引,所以position[loopCount]
不会起作用。 如何索引呢?
传递pv.Root.Parameter.Count
而不是20
作为数组长度。
string[] position = new string[pv.Root.Parameter.Count];
或使用列表 ,如果您不希望使用固定大小。
您可能需要一个“无限”数组。 使用List
而不是数组。
在您的情况下:
List<string> positions = new List<string>();
for (int i = 0; i < pv.Root.Parameter.Count; i++)
{
if (name == pv.Root.Parameter[i].Name)
{
positions.Add(name); //To get an element use positions.ElementAt(<index>)
}
}
或者,如果您需要n个元素的数组,请使用:
string[] position = new string[pv.Root.Parameter.Count]];
您可以尝试使用Linq :
String[] position = pv.Root.Parameter
.Where(item => name == item.Name)
.Select(item => item.Name)
.ToArray();
或者如果您想要List<T>
而不是数组
List<String> position = pv.Root.Parameter
.Where(item => name == item.Name)
.Select(item => item.Name)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.