[英]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.