GowthamanSS
GowthamanSS

Reputation: 1474

Remove all but the first item in a list

let us consider a list as below

list contains values as a,b,c,d....

i need a query to just remove all the values in the list other than that "a".

Upvotes: 28

Views: 29521

Answers (2)

gabba
gabba

Reputation: 2880

List<T> elements = ....

elements.RemoveAll(x => x != a)

UPD

for removing other than first you need to use RemoveRange as Tim Schmelter sayed.

or make new list with first element. elements.First()

Upvotes: 18

Tim Schmelter
Tim Schmelter

Reputation: 460058

List.RemoveRange is what you're looking for:

if(list.Count > 1)
    list.RemoveRange(1, list.Count - 1);

Demo

Upvotes: 52

Related Questions