Introduction
In this blog, we will see how we can start a list from a specific value. Before starting, let’s take a look at my list value. Below are the values in my list.
But suppose, I need to start the looping from value =4 and check all incremental values from 4. See below.
So, my list should be like this.
To achieve the above output, we need to use list properties, i.e., SkipWhile<> (to skip elements) and TakeWhile<> (to take elements).
Code
- int iStartValue = 4;
- List<int> lstValue = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
- var Output = lstValue.SkipWhile(x => x != iStartValue)
- .Concat(lstValue.TakeWhile(x => x != iStartValue))
- .ToList();
Output
Let’s look at some ideas about List and its properties like Skpi, Skipwhile, Take, TakeWhile.
What is a list in C#?
A list is a collection of items that can be accessed by index and provides functionality to search, sort, and manipulate list items.
Example
List<int> lstValue = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
In C# lists, we have two main properties,
Skip, SkipWhile
- skip
The Skip() method "skips" over the first n elements in the sequence and returns a new sequence containing the remaining elements after the first n elements.
- SkipWhile
SkipWhile() "skips" the initial elements of a sequence that meets the criteria specified by the predicate and returns a new sequence containing the first element that doesn't meet the criteria as well as any elements that follow.
Take, TakeWhile
- Take
The Take() method extracts the first n elements (where n is a parameter to the method) from the beginning of the target sequence and returns a new sequence containing only the elements taken.
- TakeWhile
TakeWhile() behaves similarly to the Take() method except that instead of taking the first n elements of a sequence, it "takes" all of the initial elements of a sequence that meet the criteria specified by the predicate, and stops on the first element that doesn't meet the criteria. It then returns a new sequence containing all the "taken" elements.
Conclusion
I have provided this information because I know such scenarios will always arise. Thanks for reading. Enjoy!