LINQ-Language Integrated Query


Introduction:

  • Linq is not c#3.0 and vice versa.
  • New language enhancement introduced in c#
  • Allow you to write structured type-safe queries over local object collections and remote data sources.
  • The basic units of linq are sequence and elements
  • Sequence- object implements the generic IEnumerable interface, Element-Each item in a sequence

Example:

    int[] valu = new int[] {10,20,30};

here the valu is a sequence and 10,20,30 are elements.

Query operator:

Query operator is a method. 

    IEnumerable<string> result = Enumerable.Where(stringarray, o => o.Length == 3);

"Where" is the query operator.
Two Types of Queries in linq:

  1. Comprehensive
  2. Lamda

Comprehension queries:

Comprehensive queries are syntactically same like sql queries but the executions flows are different.

    int[] array = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
                      var query = (from no in array
                                where (no % 3 == 0)
                                select no).ToArray();
                      foreach (int no in query)
                      {
                           Console.WriteLine(no);
                      }   


Lamda Queries:

    string[] stringarray = { "How", "are", "you" };
                  
IEnumerable<string> result = Enumerable.Where(stringarray, o => o.Length == 3);        
                  
foreach (string res in result)
                  
Console.WriteLine(res);
    (or)
    string[] stringarray = { "How", "are", "you" };
                  
IEnumerable<string> result = stringarray.Where(stringarray, o => o.Length == 3);        
                  
foreach (string res in result)
                  
Console.WriteLine(res);

Lamda queries are faster than comprehensive because internally comprehensive queries are converted to lamda queries and executed ahead.

    string[] stringarray = { "Hi", "How", "are", "you","a" };
 
    IEnumerable<string> result = stringarray
                .Where(n => n.Contains("a"))
                .OrderBy(n => n.Length)
                .Select(n => n.ToUpper());
 
    foreach (string i in result)
                Console.Write(i + ",");


Where, OrderBy, Select - Query operators

Execution start from left to right.

Mixing lamda and comprehensive queries:

In same query we can integrate comprehensive and lamda queries.

    string[] stringarray = { "Hi", "How", "are", "you","a" }; 
    int c =    (from n in stringarray
                    where stringarray.Contains("a")
                    select n).Count();
    Console.WriteLine(c);

Up Next
    Ebook Download
    View all
    Learn
    View all