问题描述
我正在寻找一种方法来满足在索引中插入值的需要,如果该索引繁忙,则数组的所有下一个值都将向下滑动:
char[] myArray = new char[5];
myArray[0] = 'a';
myArray[1] = 'b';
myArray[2] = 'c';
myArray[3] = 'd';
myArray[4] = 'e';
char missingChar = 'k';
//I want to insert the char "missingChar" in myArray[2]
//I want all the other indexes to move down,the former-myArray[2] also
Array.Resize(ref myArray,myArray.Length + 1);
myArray[0] = 'a';
myArray[1] = 'b';
myArray[2] = missingChar;
myArray[3] = 'c';
myArray[4] = 'd';
myArray[5] = 'e';
所需的输出是:
一个, 乙, 克, C, d、
有没有办法在不涉及列表的情况下做到这一点?
解决方法
Lists 会根据需要动态调整后备数组的大小,为您处理这个问题。
var myArray = new List<char>(5);
myArray.Insert(0,'a');
myArray.Insert(1,'b');
myArray.Insert(2,'c');
myArray.Insert(3,'d');
myArray.Insert(4,'e');
char missingChar = 'k';
myArray.Insert(2,missingChar);
输出:
a
b
k
c
d
e