Mattias Weiland
Mattias Weiland

Reputation: 71

Take out elements of a list up to a certain value

How can I take out all elements of a list up to a certain value, and then get a list that has the rest of the values.

Ex. List would be : 0,0,0,0,0,0,1,1,1,1,0,0

I want new List: 1,1,1,1,0,0

I believe it is using List.Skip method, but not sure.

This is my list right now, containing 0's and 1's like my example(just much bigger.)

Would it be something like :

List<string> Values;
newList=Values.Skip(X=x=>"1")

Upvotes: 0

Views: 995

Answers (3)

Henry Puspurs
Henry Puspurs

Reputation: 106

    List<string> Values;
    var newList = new List<string>;
    bool start = false;
    
    foreach (string value in Values)
    {
    if (value == "0" && start == false)
    {
    continue;
    }
    else
    {
start = true;
    newList.Add(value);
    }
    }

Might work?

Upvotes: 0

Jawad
Jawad

Reputation: 11364

You can use SkipWhile method to skip until you hit the value you want to start taking.

List<string> values = new List<string>() { "0", "0", "0", "0", "0", "0", "0", "1", "1", "1", "1", "1", "0", "0", "0", "0" };
List<string> newList = values.SkipWhile(x => !x.Equals("1")).ToList();
Console.WriteLine(string.Join(",", newList));

// Prints
1,1,1,1,1,0,0,0,0

Upvotes: 2

Sach
Sach

Reputation: 10393

If you want to get all the items starting from the first item that is 1, you can use List.IndexOf() to get the index of the first 1 that appears on your list, then use Skip() to get the rest of the items.

var list = new List<int>() { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0 };
var fromFirst1Value = list.Skip(list.IndexOf(1));

If you break it down, list.IndexOf(1) will return the index of the first 1 in your list, which in the above example is 6. Then the Skip() will get you all the elements starting from that index.

If on the other hand you simply want to get all the elements at a certain index you can simply pass that index to the Skip() method:

var fromSomeIndex = list.Skip(5);

This will return all elements in the list starting at index 5 (which is the 6th element).

Upvotes: 0

Related Questions