locked
How to use linq for "for" loop and "while" loop in C# RRS feed

  • Question

  • How to use linq for "for" loop and "while" loop in C#.

    I need it with example.

    Can some one help me out please ???


    Monday, March 4, 2013 8:36 AM

Answers

  • Here's a simple example that iterates through a collection of integer using TakeWhile function that accepts a delegate that accepts an integer and returns a boolean.  The ForEach function is then used to iterate through the result.  TakeWhile and ForEach are extension methods under the System.Linq namespace


    List<int> numbers = new List<int>();
    
    // 
    numbers.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
    
    // Iterate through each of the numbers in the collection until the condition is satisfied and place the result in a new collection.
    var result = numbers.ToList()
                        .TakeWhile(number => number <= 5);
    
    // Move through each of the result items.
    result.ToList()
          .ForEach(r =>
          {
            Debug.WriteLine(r);
          });

    Monday, March 4, 2013 3:32 PM

All replies

  • I'm going to move this to the C# forum for you.


    Jim Cheshire | Microsoft

    Monday, March 4, 2013 12:40 PM
  • Hi RupeshMca7,

    Welcome to C#! Check out the C# Iteraion Statements: http://msdn.microsoft.com/en-us/library/32dbftby.aspx

    Here you will find examples of:

    • do
    • for
    • foreach
    • in
    • while
    • Proposed as answer by Jason Dot Wang Wednesday, March 6, 2013 4:48 AM
    • Unproposed as answer by Jason Dot Wang Wednesday, March 6, 2013 4:49 AM
    Monday, March 4, 2013 1:40 PM
  • Here's a simple example that iterates through a collection of integer using TakeWhile function that accepts a delegate that accepts an integer and returns a boolean.  The ForEach function is then used to iterate through the result.  TakeWhile and ForEach are extension methods under the System.Linq namespace


    List<int> numbers = new List<int>();
    
    // 
    numbers.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
    
    // Iterate through each of the numbers in the collection until the condition is satisfied and place the result in a new collection.
    var result = numbers.ToList()
                        .TakeWhile(number => number <= 5);
    
    // Move through each of the result items.
    result.ToList()
          .ForEach(r =>
          {
            Debug.WriteLine(r);
          });

    Monday, March 4, 2013 3:32 PM