[英]How to increase index of array
我有一個數組例如
string[] data = {"1","2","3","5","6","7","4",....goes on)
假設我想做以下操作; 如果數組數據的第3個元素是5
那么將所有內容向上移動索引一個點,基本上數組就會變為
{"1","2","3","","5","6","7","4"...}
一個空白區域將占據5位。
if (data[3] == "5")
{
// move index forward one spot
}
雖然可以使用數組來完成,但可能更容易使用像List<T>
這樣的更高級別的構造,然后在需要時將其轉換回數組。 如果您根本不需要數組,則可以單獨使用List<T>
。
string[] data = {"1","2","3","5","6","7","4"};
var list = new List<string>(data);
for (var i = 0; i < list.Count; i++)
{
if (list[i] == "5")
{
list.Insert(i, "");
i++;
}
}
data = list.ToArray();
這是一個有效的演示: https : //dotnetfiddle.net/lHzgFH
這是最簡單的實現,雖然它不是最有效的 - 請參閱替代實施的一些其他答案,這可能是大數據集的更好選擇。
正如其他建議的那樣,使用List<>
,但是......
// presize, because we know that there are
// at least data.Length elements!
// technically the final array will have a size
// data.Length <= finalSize <= data.Length * 2
var list = new List<string>(data.Length);
for (var i = 0; i < data.Length; i++)
{
if (data[i] == "5")
{
list.Add("");
}
list.Add(data[i]);
}
data = list.ToArray();
List<>.Insert()
是“慢”因為你必須在插入的元素之后移動每個元素(它是一個O(n)操作)...但是技巧是你可以填充List<>
一個元素一次,所以不使用List<>.Insert()
並僅使用List<>.Add()
現在......在不創建List<>
,我們可以計算出數組的最終大小,例如:
int count5 = data.Count(x => x == "5");
string[] data2 = new string[data.Length + count5];
for (int i = 0, j = 0; i < data.Length; i++, j++)
{
if (data[i] == "5")
{
data2[j] = "";
j++;
}
data2[j] = data[i];
}
你不能用數組真正做到這一點,因為它是一個固定的大小,所以你不能讓它更大,以保持額外的空白空間。
您需要使用List<int>
(除非您有理由將數字視為字符串?),您將使用函數List<int>.IndexOf
查找'5'和List<int>.Insert
添加空白。
您甚至可能希望查看List<Nullable<int>>
因為'blank'可以用null表示。
Linq解決方案:
String[] data = { "1", "2", "3", "5", "6", "7", "4" };
// put "" before any item if it equals to "5"
var result = data
.SelectMany(item => item == "5" ? new String[] {"", item} : new String[] {item})
.ToArray();
// put "" before 3d item if it equals to "5"
var result2 = data
.SelectMany((item, index) => (item == "5" && index == 3) ? new String[] {"", item} : new String[] {item})
.ToArray();
這樣的東西可以工作:
https://msdn.microsoft.com/en-us/library/bb300583%28v=vs.110%29.aspx
“此成員是顯式接口成員實現。只有在將Array實例強制轉換為IList接口時才能使用它。”
我認為你可以將你的數組轉換為IList接口。 但是,我無法嘗試我的答案。
雖然我認為List<T>
答案是最好的,但如果您不想使用列表,這可能是更好的解決方案。 作為一個注釋,數組應該是一個靜態長度。
string[] data = {"1","2","3","5","6","7","4"};
var valueToChangeAt = 3;
//The above should be parameters, and passed into this as a separate method
Queue<String> tempHolder = new Queue<String>();
for(var i = 0; i < data.Length; i++) {
if(i >= valueToChangeAt-1)
tempHolder.Enqueue(data[i]);
}
string[] newData = new string[data.Length+1];
for(var j = 0; j < valueToChangeAt; j++)
newData[j] = data[j];
newData[valueToChangeAt-1] = "";
for(var k = valueToChangeAt; k < newData.Length; k++)
newData[k] = tempHolder.Dequeue();
//At this point return newData, allowing your stack and old array to be destroyed.
我認為這是一個合適的解決方案,你不會創建大量的新對象,你可以將它抽象為一個方法,並按照它的使用方式使用Queue
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.