如何从C中的List中删除元素# [英] How do I remove elements from List In C#
本文介绍了如何从C中的List中删除元素#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有List包含元素99,86,87,100,101,104
从这些我希望将列表中的元素从104弹出到87.
即剩余列表应为99,86。那么如何动态删除元素从104到87
解决方案
尝试:
List< int> list = new 列表< int>(){ 99 , 86 , 87 , 100 , 101 , 104 };
int index = list.IndexOf( 87 );
while (index > = 0 && index < list.Count)
{
list.RemoveAt(index);
}
从.NET 2.0开始,您可以使用'RemoveRange运算符:List< int> intList = new 列表< int> { 99 , 86 , 87 , 100 , 101 , 104 };
intList.RemoveRange(intList.IndexOf( 87 ), 4 );
您有2个选项
1.使用您的元素创建一个新列表想要
2.反向迭代列表例如
// 创建列表
列表< int> data = new List< int>();
for ( int i = 0 ; i < 100 ; i ++)
{
data.Add (一世);
}
// 删除大于90的元素
for ( int x = 99 ; x > = 0 ; x--)
{
if (data [x] > 90 )
{
int c = data [x];
data.Remove(c);
}
}
< / int > < / int > 跨度>
Hi,I have List which Contains the elements 99,86,87,100,101,104
From these I want to pop the elements from list from 104 to 87.
i.e remaining List should be 99,86. So how can I dynamically remove elements from 104 to 87
解决方案
Try:
List<int> list = new List<int>() { 99, 86, 87, 100, 101, 104 }; int index = list.IndexOf(87); while (index >= 0 && index < list.Count) { list.RemoveAt(index); }
Starting with .NET 2.0, you can use the 'RemoveRange operator:List<int> intList = new List<int>{99,86,87,100,101,104}; intList.RemoveRange(intList.IndexOf(87),4);
You have 2 options
1. Create a new list with the elements in that you want
2. iterate over the list in reverse for example
//create list List<int> data = new List<int>(); for (int i = 0; i < 100; i++) { data.Add(i); } //remove elements that are greater than 90 for(int x = 99; x >= 0; x--) { if(data[x] > 90) { int c = data[x]; data.Remove(c); } } </int></int>
这篇关于如何从C中的List中删除元素#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文