C# 删除常规数组的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/457453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove element of a regular array
提问by leora
I have an array of Foo objects. How do I remove the second element of the array?
我有一组 Foo 对象。如何删除数组的第二个元素?
I need something similar to RemoveAt()
but for a regular array.
我需要类似于RemoveAt()
但用于常规数组的东西。
采纳答案by Andrew Kennan
If you don't want to use List:
如果您不想使用 List:
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
You could try this extension method that I haven't actually tested:
你可以试试这个我没有实际测试过的扩展方法:
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
And use it like:
并像这样使用它:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);
回答by Paul Mitchell
Here's how I did it...
这是我如何做到的...
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
回答by Sebastian Dietz
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
数组的本质是它们的长度是不可变的。您不能添加或删除任何数组项。
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
您必须创建一个短一个元素的新数组,并将旧项复制到新数组中,不包括要删除的元素。
So it is probably better to use a List instead of an array.
所以最好使用 List 而不是数组。
回答by gkrogers
In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.
在普通数组中,您必须将 2 以上的所有数组条目打乱,然后使用 Resize 方法调整其大小。使用 ArrayList 可能会更好。
回答by Martin Brown
Here is an old version I have that works on version 1.0 of the .NETframework and does not need generic types.
这是我拥有的一个旧版本,它适用于.NET框架的1.0 版并且不需要泛型类型。
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
这是这样使用的:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
回答by EdHellyer
I use this method for removing an element from an object array. In my situation, my arrays are small in length. So if you have large arrays you may need another solution.
我使用此方法从对象数组中删除元素。在我的情况下,我的数组长度很小。因此,如果您有大型阵列,您可能需要另一种解决方案。
private int[] RemoveIndices(int[] IndicesArray, int RemoveAt)
{
int[] newIndicesArray = new int[IndicesArray.Length - 1];
int i = 0;
int j = 0;
while (i < IndicesArray.Length)
{
if (i != RemoveAt)
{
newIndicesArray[j] = IndicesArray[i];
j++;
}
i++;
}
return newIndicesArray;
}
回答by nawfal
Not exactly the way to go about this, but if the situation is trivial and you value your time, you can try this for nullable types.
不完全是解决此问题的方法,但如果情况微不足道并且您珍惜时间,则可以尝试为可空类型使用此方法。
Foos[index] = null
and later check for null entries in your logic..
然后检查逻辑中的空条目..
回答by Bamara Coulibaly
First step
You need to convert the array into a list, you could write an extension method like this
第一步
您需要将数组转换为列表,您可以编写这样的扩展方法
// Convert An array of string to a list of string
public static List<string> ConnvertArrayToList(this string [] array) {
// DECLARE a list of string and add all element of the array into it
List<string> myList = new List<string>();
foreach( string s in array){
myList.Add(s);
}
return myList;
}
Second step
Write an extension method to convert back the list into an array
第二步
写一个扩展方法将列表转换回数组
// convert a list of string to an array
public static string[] ConvertListToArray(this List<string> list) {
string[] array = new string[list.Capacity];
array = list.Select(i => i.ToString()).ToArray();
return array;
}
Last steps
Write your final method, but remember to remove the element at index before converting back to an array like the code show
最后步骤
编写您的最终方法,但请记住在转换回数组之前删除索引处的元素,如代码所示
public static string[] removeAt(string[] array, int index) {
List<string> myList = array.ConnvertArrayToList();
myList.RemoveAt(index);
return myList.ConvertListToArray();
}
examples codes could be find on my blog, keep tracking.
示例代码可以在我的博客上找到,请继续跟踪。
回答by infografnet
This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize<T>
:
这是一种删除数组元素的方法,从 .Net 3.5 开始,无需复制到另一个数组 - 使用相同的数组实例Array.Resize<T>
:
public static void RemoveAt<T>(ref T[] arr, int index)
{
for (int a = index; a < arr.Length - 1; a++)
{
// moving elements downwards, to fill the gap at [index]
arr[a] = arr[a + 1];
}
// finally, let's decrement Array's size by one
Array.Resize(ref arr, arr.Length - 1);
}
回答by Duncan
As usual, I'm late to the party...
像往常一样,我参加聚会迟到了......
I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.
我想在已经存在的不错的解决方案列表中添加另一个选项。=)
我认为这是扩展的好机会。
Reference:
http://msdn.microsoft.com/en-us/library/bb311042.aspx
参考:http:
//msdn.microsoft.com/en-us/library/bb311042.aspx
So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)
因此,我们定义了一些静态类,并在其中定义了我们的方法。
之后,我们可以随意使用我们的扩展方法。=)
using System;
namespace FunctionTesting {
// The class doesn't matter, as long as it's static
public static class SomeRandomClassWhoseNameDoesntMatter {
// Here's the actual method that extends arrays
public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
T[] nArray = new T[oArray.Length - 1];
for( int i = 0; i < nArray.Length; ++i ) {
nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
}
return nArray;
}
}
// Sample usage...
class Program {
static void Main( string[] args ) {
string[] myStrArray = { "Zero", "One", "Two", "Three" };
Console.WriteLine( String.Join( " ", myStrArray ) );
myStrArray = myStrArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myStrArray ) );
/* Output
* "Zero One Two Three"
* "Zero One Three"
*/
int[] myIntArray = { 0, 1, 2, 3 };
Console.WriteLine( String.Join( " ", myIntArray ) );
myIntArray = myIntArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myIntArray ) );
/* Output
* "0 1 2 3"
* "0 1 3"
*/
}
}
}