ManojRK
ManojRK

Reputation: 962

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

Say I have a list of 10 items.

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'). 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?

Edit:

A character can occur multiple times in the List. I want only the occurance at 'n' to be removed.

Upvotes: 9

Views: 6729

Answers (2)

D Stanley
D Stanley

Reputation: 152556

Sure, using the overload of Where that takes an index parameter:

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

Upvotes: 20

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

You can use Enumerable.Where method.

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.

Upvotes: 0

Related Questions