为了账号安全,请及时绑定邮箱和手机立即绑定

C# 删除元素并重新排序

C# 删除元素并重新排序

C#
Smart猫小萌 2021-12-05 16:57:37
我有一个主要收藏List<int> main = Enumerable.Range(0,11).ToList();我有 3 个列表:List<int> a = new List<int>{main[0],main[1],main[5],main[3]}; //I delete this list with all its items from the mainList<int> b = new List<int>{main[2],main[6],main[7]};List<int> c = new List<int>{main[8],main[9],main[4],main[11],main[10]};现在我想删除从主列表0,1,5,3项和我删除一个完全名单,因此我想更新 BC的。意味着他们将成为:List<int> main = new List<int> {0,1,2,4,5,6,7};List<int> b = new List<int>{main[0],main[2],main[3]};List<int> c = new List<int>{main[4],main[5],main[1],main[7],main[6]};我是否需要某种映射,也许其他人以前遇到过类似的问题?也许此屏幕截图展示了我想要做得更好的事情:在此之后,我必须更新 b 和 c 集合
查看完整描述

2 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

不清楚你想做什么,但你可以使用 LINQ 延迟评估来实现类似的事情。你不能用硬编码索引做你想做的事。您需要使用过滤器和 LINQ 方法。


List<int> main = Enumerable.Range(0,11).ToList();


List<int> a = new List<int>{ 1, 5, 3, 0, 7};

IEnumerable<int> b = main.Where(i => i % 2 == 0);

IEnumerable<int> c = main.Where(i => i % 2 == 1);


foreach (var i in b)

{

    Console.Write(i + ","); // 0, 2, 4, 6, 8, 10

}

Console.WriteLine();


foreach (var i in c)

{

    Console.Write(i + ","); // 1, 3, 5, 7, 9

}

Console.WriteLine();



foreach (var i in a)

{

    main.Remove(i);

}


foreach (var i in b)

{

    Console.Write(i + ","); // 2, 4, 6, 8, 10

}

Console.WriteLine();


foreach (var i in c)

{

    Console.Write(i + ","); // 9

}

Console.WriteLine();


查看完整回答
反对 回复 2021-12-05
?
皈依舞

TA贡献1851条经验 获得超3个赞

您可以使用LinqExcept功能。

main = main.Except(a).ToList();


查看完整回答
反对 回复 2021-12-05
  • 2 回答
  • 0 关注
  • 338 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信