简体   繁体   English

如何使用Linq获取除List中第n个元素之外的所有元素

[英]How to get all elements except the n'th element in a List using Linq

Say I have a list of 10 items. 说我有10个项目的清单。

List<char> chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];

I need a new List containing all the elements in the List except n'th (say, 3rd item 'C' ). 我需要一个新的List,其中包含列表中除n之外的所有元素(例如,第3项'C' )。 I don't want the original list to be altered since I need it later. 我不希望改变原始列表,因为我以后需要它。

Another option is, I can clone the list and remove the item, but then all the items after the n'th has to be shifted up. 另一种选择是,我可以克隆列表并删除该项目,但是然后必须将所有项目向上移动。

Is there a way to get the list using Linq? 有没有办法使用Linq获取列表?

Edit: 编辑:

A character can occur multiple times in the List. 一个字符可以在List中多次出现。 I want only the occurance at 'n' to be removed. 我只希望删除'n'处的出现。

当然,使用Where接受索引参数的重载

var allBut3 = chars.Where((c, i) => i != 2);  // use 2 since Where() uses 0-based indexing

You can use Enumerable.Where method. 您可以使用Enumerable.Where方法。

Filters a sequence of values based on a predicate. 根据谓词过滤一系列值。

List<char> chars = new List<char>(){'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
var newlist = chars.Where(n => n != chars.ElementAtOrDefault(2));

Here is a DEMO . 这是一个DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM