我有一个 Foo 对象的数组。如何删除这个数组的第二个元素?
我需要类似于 RemoveAt()
但适用于普通数组的方法。
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);
数组的本质是长度不可变的,不能添加或删除其中的任何项。
如果要删除数组中的某个元素,您需要创建一个新的比原数组长度少1的数组,并将旧的元素复制到新数组中(不包括要删除的元素)。
因此,使用List可能会更好,而不是使用数组。
List<mydatatype> array = new List<mydatatype>(arrayofmydatatype)
- Immortal BlueSystem.Linq
命名空间中的Enumerable.ToList()
方法,将@ImmortalBlue或var myList = myArray.ToList();
转换为列表。 - Dyndrilliac我使用这种方法从对象数组中移除元素。在我的情况下,我的数组长度很小。如果您有大型数组,则可能需要另一种解决方案。
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;
}
LINQ 一行解决方案:
myArray = myArray.Where((source, index) => index != 1).ToArray();
在这个例子中,1
是要移除的元素的索引--在本例中,根据原始问题,是第二个元素 (在 C# 的从零开始的数组索引中,1
是第二个元素)。
一个更完整的例子:
string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();
执行该代码片段后,myArray
的值将为 { "a", "c", "d", "e" }
。
这是一种在 .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);
}
Resize
方法时需要使用ref
的原因。数组实例的长度是固定且不可变的。 - Jeppe Stig Nielsen这是我拥有的旧版本,适用于1.0版本的.NET框架,不需要泛型类型。
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]);
}
}
虽然这不是最佳解决方式,但如果情况比较琐碎且你很看重时间,你可以在可空类型中尝试这种方法。
Foos[index] = null
然后在您的逻辑中检查空条目。
尝试下面的代码:
myArray = myArray.Where(s => (myArray.IndexOf(s) != indexValue)).ToArray();
或者
myArray = myArray.Where(s => (s != "not_this")).ToArray();
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"
*/
}
}
}
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;
}
System.Collections.ObjectModel.Collection<Foo>
。 - abatishchev