CSharp - LINQ Query Expressions

Introduction

SQL-like syntax is available for LINQ queries.

This syntax is provided via the C# language enhancement known as query expressions.

To perform a LINQ query, it is not required to use query expressions.

The alternative is standard C# dot notation, calling methods on objects and classes.

The following code shows a query using the standard dot notation syntax.

Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Program/*from  w w w.  j a  va2 s.  co m*/
{
    static void Main(string[] args)
    {
        string[] names = { "Python", "Java", "Javascript", "Bash", "C++", "Oracle" };

        IEnumerable<string> sequence = names
            .Where(n => n.Length < 6)
            .Select(n => n);

        foreach (string name in sequence)
        {
            Console.WriteLine("{0}", name);
        }
    }
}

Result

The following code is the equivalent query using the query expression syntax.

Demo

using System;  
using System.Collections.Generic;
using System.Linq;  
class Program/*from   ww w . ja  v a 2s .co  m*/
{
    static void Main(string[] args)
    {
      string[] names = {   
        "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};  
        
      IEnumerable<string> sequence = from n in names  
                                     where n.Length < 6  
                                     select n;  
        
      foreach (string name in sequence)  
      {  
        Console.WriteLine("{0}", name);  
      }  

    }
}

Result

Related Topics