开发者

Trying to get all elements after first match using linq

开发者 https://www.devze.com 2022-12-23 03:11 出处:网络
How do I retrieve all elements after the first one not starting with a \"-\" using linq? var arr = new[] {\"-s1\", \"-s2\", \"va\", \"-s3\", \"va2\", \"va3\"};

How do I retrieve all elements after the first one not starting with a "-" using linq?

var arr = new[] {"-s1", "-s2", "va", "-s3", "va2", "va3"};
var allElementsAfterVA = from a in arr where ???? select a;

I w开发者_如何转开发ant allElementsAfterVA to be "-s3", "va2", "va3"


To find all of the arguments after the first that does NOT start with "-", you can do:

var elementsAfterFirstNonDash = arr.SkipWhile(i => i[0] != '-').Skip(1);

This finds "va", then skips it via Skip(1). The rest of the arguments will be returned.


Can you please be more clear? If I understood correctly, the first one starting with a "-" is "-s1", so the elements after this would be "-s2", "va", "-s3", "va2", "va3" and not "-s3", "va2", "va3"


I don't quite get the question from your text, but looking at the example: Did you look at SkipWhile()? Seems to be related/useful?


arr.Where((n, i) => i > 0 && n.StartsWith("-"))

yields

-s2 -s3

Is this what you meant?

0

精彩评论

暂无评论...
验证码 换一张
取 消