C#移除List中特定元素
在List里面移除其中一个元素之后,原有的索引以及索引对应的值会发生改变,如果按照原有的索引值删除,就会误删除其它元素。
1.实现思路
原始List为A,将需要删除的元素放到一个List B里面,遍历此List,A再使用Remove依次移除元素。下面代码实现的是移除比新插入的seq小2的元素
2.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace PracticeProject
{
internal class Program
{
static void Main(string[] args)
{
ListTest();
Console.ReadLine();
}
public static void ListTest()
{
//定义一个元素为Test的集合tests
List<Test> tests = new List<Test>();
//向List里面添加元素
Test test = new Test();
test.seq = 1; ;
test.content = "第一";
tests.Add(test);
Test test1 = new Test();
test1.seq = 2; ;
test1.content = "第二";
tests.Add(test1);
Test test2 = new Test();
test2.seq = 3; ;
test2.content = "第三";
tests.Add(test2);
Test test3 = new Test();
test3.seq = 4; ;
test3.content = "第四";
tests.Add(test3);
Console.WriteLine("移除之前");
for (int i = 0; i < tests.Count; i++)
{
Console.WriteLine(tests[i].seq + " " + tests[i].content + " 序列号" + i);
}
tests.Remove(tests[1]);
Console.WriteLine("移除索引为1的元素");
for (int i = 0; i < tests.Count; i++)
{
Console.WriteLine(tests[i].seq + " " + tests[i].content + " 序列号" + i);
}
//定义一个元素类型为Test的集合reamoveList,存放需要删除的元素
List<Test> reamoveList = new List<Test>();
int maxValue = tests[tests.Count - 1].seq - 2;
for (int i = 0; i < tests.Count; i++)
{
if (tests[i].seq <= maxValue)
{
reamoveList.Add(tests[i]);
}
}
for (int i = 0; i < reamoveList.Count; i++)
{
//删除tests中的元素
tests.Remove(reamoveList[i]);
}
Console.WriteLine("移除之后");
for (int i = 0; i < tests.Count; i++)
{
Console.WriteLine(tests[i].seq + " " + tests[i].content + " 序列号" + i);
}
}
}
public class Test
{
public int seq { get; set; }
public string content { get; set; }
}
}
3.运行结果
posted on 2023-07-14 09:50 GoodPrintf 阅读(1597) 评论(0) 编辑 收藏 举报