简体   繁体   中英

How to declare dynamic array in c#

I am working on silverligth5 (my previous experience is c++)and i have to create a dynamic array whose size is decided dynamically.

Until i have everything static and it's like this:

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

As it can be seen that the way i do will have size 20 only and i want it to be only of the same length as pv.Root.Parameter.Count .

How to achieve this ?

EDIT/ the problem when i try to achieve it through list : I have problem at this line :

if (pv.Root.Parameter[loopCount].Name == position[loopCount])
{ 
   rowGrid.Opacity=0.3;
}

Because surely it will not work position[loopCount] because position is a List and cannot be indexed like this. How to index it ?

pass the pv.Root.Parameter.Count instead of 20 as the array length.

string[] position = new string[pv.Root.Parameter.Count];

Or use a list , if you don't want a fixed size.

You probably want an "infinite" array. Use a List instead of an array.

In your case:

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

Or if you need an array of n elements use:

string[] position = new string[pv.Root.Parameter.Count]];

You can try using Linq :

String[] position = pv.Root.Parameter
  .Where(item => name == item.Name)
  .Select(item => item.Name)
  .ToArray();

Or if you want List<T> and not array

List<String> position = pv.Root.Parameter
  .Where(item => name == item.Name)
  .Select(item => item.Name)
  .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM