Reputation: 464
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
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
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
Reputation: 391326
You can use this LINQ expression:
myList.SkipWhile(c => c != '(').Skip(1).TakeWhile(c => c != ')')
^----- 1 --------------^ ^- 2 -^ ^-------- 3 -----------^
(
(
we found)
(which will not be included)Notes:
Upvotes: 7
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