2008/03/06

[C#]從陣列中移除一行值

原始連結


static void Main(string[])
{
//array 是固定的,不能動態去變更大小
//只能重新宣告一個新的陣例才能達到你 Remove 的需求
//一般如果是動態的,會用 ArrayList 或是 List<> 來做
string[] aryStr = { "A", "B", "C", "D" };
int removeIndex = 2;//把 C 移掉
// ======= sample 1 ==> 改用 List<string> ====
List<string> list = new List<string>();
foreach (string str in aryStr)
{
list।Add(str);
}
list।RemoveAt(removeIndex);
string[] aryStrRemoveByList = list।ToArray();
foreach (string str in aryStrRemoveByList)
{
Console।WriteLine(str);
}
Console।WriteLine(new String('=', 20));
// ======== sample 2 自已寫Method去轉,不過還是要new新的
string[] aryStrRemoveByArray = new string[aryStr।Length - 1];
int count = 0;
for (int i = 0; i < aryStr।Length; i++)
{
if (i != removeIndex)
{
aryStrRemoveByArray[count] = aryStr[i];
count++;
}
}
foreach (string str in aryStrRemoveByArray)
{
Console।WriteLine(str);
}
}

沒有留言: