Nightscape
Nightscape

Reputation: 464

Get all values between two specific values in a list

I have a char list:

var myList = new List<char>(new[] { 'x', 'y', '(', 'a', 'b', 'c', ')', 'z' });

With the values:

 'x'
 'y'
 '('
 'a'
 'b'
 'c'
 ')'
 'z' 

How can i take all the values between the braces? The values in new list should look like this:

 'a'
 'b'
 'c'

The index of the braces in the list can change every session.

Upvotes: 0

Views: 2024

Answers (4)

郭一凡
郭一凡

Reputation: 36

var myList = new List<char>(new[] { 'x', 'y', '(', 'a', 'b', 'c', ')', 'z' });
var start = myList.FindIndex((c) => c == '(');
var end = myList.FindIndex((c) => c == ')');
if (start != -1 && end != -1 && start < end)
{
     var result = myList.GetRange(start + 1, end - start - 1));
}
else
{
    // return null or throw error
}

Upvotes: 0

Eli
Eli

Reputation: 4926

You can also do it in a few steps:

int start = myList.IndexOf('(') + 1;
int end = myList.IndexOf(')');
var result = myList.Skip(start).Take(end - start).ToList();

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391326

You can use this LINQ expression:

myList.SkipWhile(c => c != '(').Skip(1).TakeWhile(c => c != ')')
       ^----- 1 --------------^ ^- 2 -^ ^-------- 3 -----------^
  1. Skip until we find the (
  2. Skip past the ( we found
  3. Take elements until we find the ) (which will not be included)

Notes:

  1. If the sequence contains no starting parenthesis, an empty sequence will be returned
  2. If the sequence contains no matching end parenthesis, the rest of the sequence will be returned

Upvotes: 7

Suhel Patel
Suhel Patel

Reputation: 241

You can create a loop which took '[' (open bracket) if you found it then until you don't found close bracket ']' add character to another array.

Upvotes: 0

Related Questions