简体   繁体   中英

Trying to get all elements after first match using linq

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 want 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM