Notaras
Notaras

Reputation: 717

c# remove everything in List collection after a particular index

I want to be able to remove all elements in a List<string> after a certain index

List<string> s_array= new List<string>();
s_array.Add("a");
s_array.Add("x");
s_array.Add("c");
s_array.Add("y");
s_array.Add("e");
s_array.Add("e");
s_array.RemoveAll(/* what goes here?*/);

What can i put in RemoveAll to achieve this? for example say i wanted to cut out everything from c onwards?

Upvotes: 0

Views: 3069

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Not sure what all your parameters are, so it's hard to say what approach will be best.

Using RemoveAll(), you could do:

s_array.RemoveAll(x => s_array.IndexOf(x) > s_array.IndexOf("c"));

Upvotes: 1

jazb
jazb

Reputation: 5791

You could use the key words Take or Skip to help - Example:

var s_array = new List<string> {"a","x","c","y","e","e" };

var sorted = (from x in s_array orderby x select x);

var first3 = sorted.Take(3);

var last2 = sorted.Take(2).Skip(5);

Upvotes: 1

Related Questions