从列表中删除最多一次项目

时间:2017-01-06 12:33:55

标签: c# linq

我有一个整数列表,我想只删除该列表中的一个项目,而不是重复项目。该列表是动态的,所以我不知道项目索引位置。

public List<int> checkpass (int a, int b, int c, int d, ... int z, int remove1, remove2)
{
    List<int> mylist = new List<int>(){a,b,c,d,....,z};
    // For Example 
    //List<int> mylist = new List<int>(){1,2,0,4,0,7,0,1};
    mylist.Remove(remove1); // 0
    mylist.Remove(remove2); // 4
}

此输出应为:

1,2,0,7,0,1

5 个答案:

答案 0 :(得分:4)

怎么样:

myList.RemoveAt(myList.indexOf(0));

更通用的版本是:

void RemoveFirst<T>(List<T> list, T item)
{
    var indexOfItem = list.IndexOf(item);

    if(indexOfItem != -1)
        list.RemoveAt(indexOfItem);
}

注意:.Remove()对每个人来说都很清楚。但是当人们想要看到它背后的逻辑时,我认为我的答案仍然有一些价值。

答案 1 :(得分:4)

问题代码段中的代码已经执行了您想要的操作:

mylist.Remove(0);

将光标放在Remove并点击F12。这会将您带到List<>.Remove()的文档:

  

摘要:从System.Collections.Generic.List&lt;&gt;中删除特定对象的第一个匹配项。

答案 2 :(得分:2)

您的代码确实已经这样做了,因为List<T>.Remove只删除列表中第一次出现的元素:

List<int> mylist = new List<int>(){1,2,0,4,0,7,0,1};
mylist.Remove(0);

Console.WriteLine(mylist);

输出(使用LINQPad)

1 2 4 0 7 0 1 

答案 3 :(得分:1)

正如已经指出的那样,

myList.Remove(0);

的工作原理。请注意,C#区分大小写,所以

myList.remove(0);

不起作用!

答案 4 :(得分:0)

Elements found in arr1:
set([1, 2, 3, 5])
Sublists of arr3:
[2, 3, 1]
[1, 3]
[5]