如何在列表中使用 foreach 循环,但某些索引处的元素除外

本文关键字:索引 元素 列表 循环 foreach | 更新日期: 2023-09-27 18:37:01

我在列表中有foreach循环,如下所示:

foreach( var e in myList){
//do something here but except  element at myList[0]
}

现在我需要省略第一个索引处元素的循环。我怎样才能做到这一点?

如何在列表中使用 foreach 循环,但某些索引处的元素除外

像这样的东西?

foreach(var e in myList.Skip(1)){
}

> 如果您需要使用 for 跳过任意索引处的元素会更合适:

for(var index = 0; index < myList.Count; index++){
     if (ShouldSkip(index))
          continue;
     // handle other elements as normal
}

如果您需要先跳过 - 请使用 .跳过(1) 如 https://stackoverflow.com/a/27884993/477420 所示

如果要将foreach与任意索引一起使用,可以使用.Where进行过滤:

 foreach(var e in myList.Where((item, index) => index < 3 || index > 7))
 {
    ...
 }
你也可以

尝试使用它:

foreach(var item in itemsList.Except(itemsToOmitList)){}

使用上述方法的好处是,您将能够省略多个项目,而不管它们的索引如何。