Convert a foreach loop to LINQ in C# – Code Example

Total
0
Shares

We can convert a foreach loop to LINQ in C# using defined syntax of linq. The Linq query works when there is IEnumerable in foreach loop.

What is LINQ?

LINQ stands for Language Integrated Query. It integrates SQL like queries into C# code directly. This makes the code more readable, short and easy.

Suppose you have a c# foreach loop using IEnumerable –

public void loopMethod() {

  List<string> superheroes = new List<string>() {"Ironman", "Hulk", "Superman", "Flash"};

  IEnumerable<string> enumerable()
  {
    foreach (var superhero in superheroes)
    {
       yield return superhero;
    }

    yield break;
  } 
}

We can convert it into LINQ syntax, like this –

public void loopMethod() {

  List<string> superheroes = new List<string>() {"Ironman", "Hulk", "Superman", "Flash"};

  IEnumerable<string> enumerable()
  {
    return from string superhero in superheroes
           select superhero;
  } 
}

In more generic form, you can use this –

// Generic List 👇
List<T> listName = new List<T>() {... list items ...};

// Foreach Syntax 👇
foreach(var singleItem in listName) yield return singleItem;

// LINQ Syntax 👇
return from T singleItem in listName select singleItem;

We can also use conditions in LINQ. For example, if there is a condition in foreach for only returning the strings of length > 5 then, linq uses where keyword with condition.

// Foreach with condition 👇
foreach (var superhero in superheroes)
{
    if(superhero.length > 5)
        yield return superhero;
}

// LINQ with where 👇
return from string superhero in superheroes
       where superhero.length > 5
       select superhero;

We can also use the linq call form which is slightly different. Here it is –

// linq call form 👇
return superheroes
       .Where(superhero => superhero.length > 5)
       .Select(superhero => superhero);