给出以下代码:
List<int> Data = new List<int>();
Data.Add(1);
Data.Add(2);
Array[] tmp = new Array[Data.Count];
tmp[0] = Data.ToString().ToArray();
如何访问Data
中的tmp[0]
数组?
我已尝试tmp[0,0]
或tmp[0].Data[0]
但它不起作用并给我一个错误。
简单的是我可以将数组添加到数组onedimesion吗?如果可以怎么样?
答案 0 :(得分:3)
Just write
Array tmp;
tmp = Data.ToArray();
for(int x = 0; x < tmp.Length; x++)
Console.WriteLine(tmp.GetValue(x));
However I recommend to stick at using a strong typed List
Going deeper along this slippery path you could create an Array of Array (oh boy this start to get confusing)
// Create an array of two Array
Array[] tmp = new Array[Data.Count];
// First array set to the integer array
tmp[0] = Data.ToArray();
// Second array of strings
tmp[1] = new string[5];
// Set first element of the second array to a string
tmp[1].SetValue("Steve", 0);
Again, forget this approach and use more advanced collection classes like
答案 1 :(得分:1)
If you want to access your data a a specific position just use
Data[Index]
if you realy want to use a array you can do
int[] array = Data.ToArray();
答案 2 :(得分:1)
必须这样做。
List<int> Data = new List<int>();
Data.Add(1);
Data.Add(2);
int[] tmp = Data.ToArray();
答案 3 :(得分:0)
只需使用
即可var array=Data.ToArray();
如果您想在数组中添加新项目,可能需要先使用
调整其大小Array.Resize(ref array, array.Count() + 1);
array[array.Count()]=//your items here..
答案 4 :(得分:0)
添加时。删除使用List<T>
:
List<int> Data = new List<int>();
// Add item after item
Data.Add(1);
Data.Add(2);
// Add whole range of items, e.g. an array
Data.AddRange(new int[] {3, 4, 5});
int v = Data[0];
Data[0] = v + 10;
Console.Write(String.Join(", ", Data));
最后,当你有一个数组
int[] tmp = Data.ToArray();
// you still can read an item
int x = tmp[0];
// and write it
tmp[0] = x - 10;
但请记住,您无法tmp.Add()
或tmp.RemoveAt()