Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get all elements after first match using linq

Tags:

c#

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"

like image 965
MatteS Avatar asked Mar 11 '10 20:03

MatteS


People also ask

Which function is used to get first record in LINQ collection?

Syntax of LINQ FIRST () method The syntax of the first method to get the first element from the list is: int result = objList. First();

How to use Take and skip in LINQ?

The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.

What does first() do in C#?

The First() method returns the first element of a collection, or the first element that satisfies the specified condition using lambda expression or Func delegate. If a given collection is empty or does not include any element that satisfied the condition then it will throw InvalidOperation exception.


1 Answers

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.

like image 63
Reed Copsey Avatar answered Sep 20 '22 13:09

Reed Copsey