Thursday 23 May 2013

.Net Tips : LINQ TakeWhile Method Example With C#.Net and VB.Net

You can get element from array until your given condition is satisfied.
TakeWhile LINQ method to return elements starting from the beginning of the array until a number is read whose value satisfied according to our given criteria.


Here is LINQ "TakeWhile" Method example.

In this example we take one integer array "arrayNumbers" which contains several integer values. Now we use "TakeWhile" method to get element until element value less than 6. You can see this in output.

C#. Net Example :
        int[] arrayNumbers = { 4, 5, 2, 3, 9, 8, 7, 6, 2, 0 };

        var objResult = arrayNumbers.TakeWhile(n => n < 6);

        Response.Write("<b>Numbers less than 6 : </b>");
        Response.Write("<br/>");
        foreach (var num in objResult)
        {
            Response.Write(num);
            Response.Write("<br/>");
        }

VB.Net Examples :
        Dim arrayNumbers As Integer() = {4, 5, 2, 3, 9, 8, 7, 6, 2, 0}

        Dim objResult = arrayNumbers.TakeWhile(Function(n) n < 6)

        Response.Write("<b>Numbers less than 6 : </b>")
        Response.Write("<br/>")
        For Each num As Integer In objResult
            Response.Write(num)
            Response.Write("<br/>")
        Next

Output : 
LINQ TakeWhile Method Example

No comments:

Post a Comment