删除常规数组的元素

我有一个 Foo 对象的数组。如何删除数组的第二个元素?

我需要一些类似于 RemoveAt()的东西,但一个正则的数组。

493503 次浏览

我是这么做的。

    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;
}

数组的本质是它们的长度是不可变的。您不能添加或删除任何数组项。

您必须创建一个短一个元素的新数组,并将旧项复制到新数组中,但不包括要删除的元素。

因此,最好使用 List 而不是数组。

在一个普通的数组中,你必须将所有2以上的数组条目洗牌,然后使用 Resize 方法调整它的大小。您最好使用数组列表。

如果不想使用 List:

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

你可以试试这个我还没有实际测试过的扩展方法:

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;
}

像这样使用它:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);

下面是我的一个旧版本,它可以在 .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;
}

这是这样使用的:

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]);
}
}

我使用此方法从对象数组中删除元素。在我的情况下,我的数组的长度很小。因此,如果您有大型数组,您可能需要另一种解决方案。

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;
}

这并不完全是解决这个问题的方法,但是如果情况很简单,并且您珍惜自己的时间,那么您可以对可空类型尝试这种方法。

Foos[index] = null

然后检查逻辑中的空项。

第一步
你需要把数组转换成一个列表,你可以写一个像这样的扩展方法

// 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;
}

第二步
编写一个扩展方法将列表转换回数组

// 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;
}

最后一步
编写最后一个方法,但记住在转换回数组(如代码所示)之前删除 index 处的元素

public static string[] removeAt(string[] array, int index) {


List<string> myList = array.ConnvertArrayToList();
myList.RemoveAt(index);
return myList.ConvertListToArray();
}

示例代码可以在 我的博客上找到,保持跟踪。

这是一种删除数组元素的方法。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);
}

和往常一样,我迟到了。

我想在已经存在的漂亮解决方案列表中添加另一个选项。 =)
我认为这是扩展的好机会

参考文献: Http://msdn.microsoft.com/en-us/library/bb311042.aspx

因此,我们定义了一些静态类,其中包括我们的 Method。
之后,我们可以随意使用扩展方法。 =)

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"
*/
}
}
}

LINQ 一行解决方案:

myArray = myArray.Where((source, index) => index != 1).ToArray();

该示例中的 1是要删除的元素的索引——在本示例中,根据最初的问题,是第2个元素(1是基于 C # zero 的数组索引中的第二个元素)。

一个更完整的例子:

string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();

在运行该代码片段之后,myArray的值将为 { "a", "c", "d", "e" }

    private int[] removeFromArray(int[] array, int id)
{
int difference = 0, currentValue=0;
//get new Array length
for (int i=0; i<array.Length; i++)
{
if (array[i]==id)
{
difference += 1;
}
}
//create new array
int[] newArray = new int[array.Length-difference];
for (int i = 0; i < array.Length; i++ )
{
if (array[i] != id)
{
newArray[currentValue] = array[i];
currentValue += 1;
}
}


return newArray;
}

下面是我根据一些现有的答案生成的一个帮助器方法的小集合。它利用扩展和静态方法,并带有参考参数,以获得最大的理想性:

public static class Arr
{
public static int IndexOf<TElement>(this TElement[] Source, TElement Element)
{
for (var i = 0; i < Source.Length; i++)
{
if (Source[i].Equals(Element))
return i;
}


return -1;
}


public static TElement[] Add<TElement>(ref TElement[] Source, params TElement[] Elements)
{
var OldLength = Source.Length;
Array.Resize(ref Source, OldLength + Elements.Length);


for (int j = 0, Count = Elements.Length; j < Count; j++)
Source[OldLength + j] = Elements[j];


return Source;
}


public static TElement[] New<TElement>(params TElement[] Elements)
{
return Elements ?? new TElement[0];
}


public static void Remove<TElement>(ref TElement[] Source, params TElement[] Elements)
{
foreach (var i in Elements)
RemoveAt(ref Source, Source.IndexOf(i));
}


public static void RemoveAt<TElement>(ref TElement[] Source, int Index)
{
var Result = new TElement[Source.Length - 1];


if (Index > 0)
Array.Copy(Source, 0, Result, 0, Index);


if (Index < Source.Length - 1)
Array.Copy(Source, Index + 1, Result, Index, Source.Length - Index - 1);


Source = Result;
}
}

在性能方面,它是不错的,但它可能还有改进的余地。Remove依赖于 IndexOf,并且通过调用 RemoveAt为您希望删除的每个元素创建一个新数组。

IndexOf是唯一的扩展方法,因为它不需要返回原始数组。New接受某种类型的多个元素来生成所述类型的新数组。所有其他方法都必须接受原始数组作为引用,因此事后不需要分配结果,因为这已经在内部发生了。

我本来可以定义一个合并两个数组的 Merge方法; 但是,通过传入一个实际的数组和多个单独的元素,使用 Add方法已经可以实现这一点。因此,Add可以用以下两种方式连接两组元素:

Arr.Add<string>(ref myArray, "A", "B", "C");

或者

Arr.Add<string>(ref myArray, anotherArray);

我知道这篇文章已经有十年的历史了,因此可能已经过时了,但是我会试着这样做:

使用 IEnumable。在 System 中找到 Skip ()方法。林强。它将跳过数组中选定的元素,并返回数组的另一个副本,该副本仅包含所选对象以外的所有内容。然后对每个要删除的元素重复这个步骤,然后将其保存到一个变量中。

例如,如果我们有一个名为“ Sample”(类型为 int [])的数组,其中有5个数字。我们想删除第二个,所以尝试“样本。“跳过(2) ;”应返回相同的数组,除了没有第2个数字。

尝试以下代码:

myArray = myArray.Where(s => (myArray.IndexOf(s) != indexValue)).ToArray();

或者

myArray = myArray.Where(s => (s != "not_this")).ToArray();