C#如何获取从特定值最后一次出现位置起始的列表子集
问题分析与解决方案
你的代码逻辑错误在于混淆了列表的索引值和元素的Id属性:FindLastIndex返回的是最后一个"Start"元素在列表中的位置(从0开始的索引),但你用item.Id >= indexLatestStart做判断,这完全是两个不同维度的值(比如最后一个"Start"的索引是3,而它的Id是117),导致逻辑完全失效。
以下是几种正确的实现方式:
方式一:修正遍历逻辑(保留原循环风格)
通过循环遍历列表的索引,判断当前索引是否大于等于目标索引:
List<Sample> sampleList = new() { new Sample(){ Id = 101, Action = "Start", Quantity = 1 }, new Sample(){ Id = 105, Action = "Add", Quantity = 3 }, new Sample(){ Id = 112, Action = "Start", Quantity = 4 }, new Sample(){ Id = 117, Action = "Start", Quantity = 4 }, new Sample(){ Id = 125, Action = "Add", Quantity = 2 }, new Sample(){ Id = 133, Action = "Subtract", Quantity = 1 }, new Sample(){ Id = 158, Action = "Subtract", Quantity = 1 } }; int indexLatestStart = sampleList.FindLastIndex(x => x.Action == "Start"); List<Sample> newList = new(); for (int i = 0; i < sampleList.Count; i++) { if (i >= indexLatestStart) { newList.Add(sampleList[i]); } }
方式二:使用List内置的GetRange方法(最简洁)
利用GetRange直接从指定索引截取子集:
int indexLatestStart = sampleList.FindLastIndex(x => x.Action == "Start"); // 参数:起始索引,需要截取的元素数量 List<Sample> newList = sampleList.GetRange(indexLatestStart, sampleList.Count - indexLatestStart);
方式三:使用LINQ的Skip方法(适合链式操作)
需要先引用System.Linq命名空间,通过Skip跳过前面的元素:
using System.Linq; // ... int indexLatestStart = sampleList.FindLastIndex(x => x.Action == "Start"); List<Sample> newList = sampleList.Skip(indexLatestStart).ToList();
以上三种方式都能得到你期望的结果:
Id = 117, Action = "Start", Quantity = 4 Id = 125, Action = "Add", Quantity = 2 Id = 133, Action = "Subtract", Quantity = 1 Id = 158, Action = "Subtract", Quantity = 1
内容的提问来源于stack exchange,提问作者Patee Gutee
相关产品推荐
相关产品推荐

