如何从List <int []>中删除int []?

时间:2015-06-23 08:21:18

标签: c# arrays list

我在C#中使用List作为数组非常新。所以我在使用它时遇到了问题。

我尝试使用int[]List<int[]>删除Remove整数数组)但未能删除{{1}来自int[]

这是代码:

List<int[]>

这只是一个错误吗? 或者它没有识别List<int[]> trash = new List<int[]>() { new int[] {0,1}, new int[] {1,0}, new int[] {1,1} }; int[] t1 = {0,1}; trash.Remove(t1);

8 个答案:

答案 0 :(得分:5)

问题是每个数组类型都是引用类型,List基于相等性删除项,其中引用类型的相等性默认为引用相等。这意味着,您必须删除与列表中相同的数组。

以下例如非常有效:

int[] t1 =  {0,1};
List<int[]> trash = new List<int[]>()
{
            t1,
            new int[] {1,0},
            new int[] {1,1}
};
trash.Remove(t1);

答案 1 :(得分:4)

如果要删除与目标列表具有相同内容(按相同顺序)的所有列表,可以使用Arguments以及Linq的List.RemoveAll()

进行删除。
SequenceEqual()

但这很慢。如果可以,最好使用索引。

答案 2 :(得分:2)

错误是数组列表使用引用类型数据。因此请使用List的removeAt方法,如下所示:

List<int[]> trash = new List<int[]>()
{
    new int[] {0,1},
    new int[] {1,0},
    new int[] {1,1}
};
trash.RemoveAt(0);

使用RemoveAt,您需要传递要从列表中删除的整数数组的索引。

答案 3 :(得分:0)

您的t1变量是数组的新实例。所以它不会等于列表中的第一个元素。

尝试:

trash.Remove(trash[0]);

trash.RemoveAt(0);

答案 4 :(得分:0)

.Remove方法查看元素的地址。如果它们相等,则删除。你应该这样做。

int[] t1 =  {0,1};
int[] t2 =new int[] {1,0};
int[] t3 =new int[] {1,1};
List<int[]> trash = new List<int[]>()
{
     t1,t2,t3      
};

trash.Remove(t1);

答案 5 :(得分:0)

foreach(var x in trash)
{
    if(x[0] == t1[0] && x[1] == t[1])
    {
        trash.Remove(x);
        break;
     }
}

这应该起作用

答案 6 :(得分:0)

这只是因为您正在尝试删除新项目。

它的地址引用与列表中已有的对象不同。这就是它不被删除的原因。

Int是值类型.. Int []是引用类型..

所以当你使用Int list

List<int> trash = new List<int>(){ 1, 13, 5 };
int t1 = 13;
trash.Remove(t1);//it will removed

但对于Int []

List<int[]> trash = new List<int[]>()
{
    new int[] {0,1},
    new int[] {1,0},
    new int[] {1,1}
};
var t1 = {0,1};
trash.Remove(t1);//t1 will not removed because "t1" address reference is different than the "new int[] {0,1}" item that is in list.

删除 -

trash.Remove(trash.Find(a => a.SequenceEqual(t1)));

SequenceEqual()通过使用类型的默认相等比较器来比较元素,确定两个序列是否相等。

答案 7 :(得分:0)

如果你想删除确切的序列,但你没有可能删除确切的对象(来自其他地方的序列),你可以使用lambda表达式或匿名方法搜索正确的序列:

$ /usr/bin/python3
>>> import platform
>>> platform.linux_distribution()
('Ubuntu', '14.04', 'trusty')
相关问题