Reputation: 8098
I am splitting a string like this:
string[] elements = templine.Split
(space, StringSplitOptions.RemoveEmptyEntries);
How can I get every element from templine
except for [1]
and assign it to string[] elements
?
Upvotes: 1
Views: 3100
Reputation: 27608
Well, you could either ask your brother Jon
Or you could do something like this:
var elements = templine.Split(space, StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray();
This will give you an array that contains all but the first element. If you want the first, but not the second (as your question sort of suggests), you could do this:
var allElements = templine.Split(space, StringSplitOptions.RemoveEmptyEntries);
var someElements = allElements.Take(1).Concat(allElements.Skip(2)).ToArray();
Upvotes: 0
Reputation: 30750
After your code above:
elements = elements.Take(1).Concat(elements.Skip(2)).ToArray();
One thing I want to point out: Take
and Skip
will not throw errors even if the original elements
is too short; they'll simply produce empty IEnumerable
s (which can be safely concatenated, and whose methods can be safely called).
Upvotes: 0
Reputation: 128317
Lots of crazy LINQ examples here. This should probably be more efficient, if that matters to you:
public static T[] SkipElement<T>(this T[] source, int index)
{
// Leaving out null/bounds checking for brevity.
T[] array = new T[source.Length - 1];
Array.Copy(source, 0, array, 0, index);
Array.Copy(source, index + 1, array, index, source.Length - index - 1);
return array;
}
With this you could do:
string[] elements = templine.Split(space, StringSplitOptions.RemoveEmptyEntries);
elements = elements.SkipElement(1);
Upvotes: 3
Reputation: 13947
string[] elements = templine.Split(space).Where((s, i) => i != 1).ToArray();
Upvotes: 6
Reputation: 52788
Using Linq, you can just do
IEnumerable<String> elements =
empline.Split(space, StringSplitOptions.RemoveEmptyEntries);
String[] result =
elements
.Take(1)
.Concat(elements
.Skip(2))
.ToArray();
Upvotes: 0
Reputation: 68667
string[] elements = templine.Split
(space, StringSplitOptions.RemoveEmptyEntries).Where(s => s != "[1]").ToArray();
if you mean you'd like to remove the second element
string[] elements = templine.Split
(space, StringSplitOptions.RemoveEmptyEntries).Where((s, i) => i != 1).ToArray();
Upvotes: 0
Reputation: 24713
List<String> elements = templine.Split
(space, StringSplitOptions.RemoveEmptyEntries).
ToList().
RemoveAt(1);
If you feel the need to go back to an array...
string[] elements = templine.Split
(space, StringSplitOptions.RemoveEmptyEntries).
ToList().
RemoveAt(1).
ToArray();
Upvotes: 1
Reputation: 12596
If you can use Linq, you can probably do:
IEnumerable<string> elements = templine.Split(...).Take(1).Skip(1);
Upvotes: 0