How To Start a List From a Specific Value In C#

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.

C#

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.

C#

To achieve the above output, we need to use list properties, i.e., SkipWhile<> (to skip elements) and TakeWhile<> (to take elements).

Code

  1. int iStartValue = 4;  
  2. List<int> lstValue = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };  
  3. var Output = lstValue.SkipWhile(x => x != iStartValue)  
  4. .Concat(lstValue.TakeWhile(x => x != iStartValue))  
  5. .ToList();  

Output

C#

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.

    C#

  • 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.

    C#

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.

    C#
  • 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.

    C#

Conclusion

I have provided this information because I know such scenarios will always arise. Thanks for reading. Enjoy!