Linq

What is Linq

Linq allows us to query a collection implementing IEnumerable<T> with SQL like syntax.

We can write condition criteria, do the sorting and so on.

A Linq query has two parts. The first is data and the other is query operators.

The data could be an array, a list.

The operators are defined as static extension methods in System.Linq.Enumerable.

LINQ also supports data from a remote server, such as a SQL Server.

These collections additionally implement the IQueryable<T> interface.

A matching set of query operators is in the Queryable class.

In the following code we apply the Where operator on an array.

The query extracts those whose length is at least four characters.

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        string[] names = { "C", "Java", "C#", "Javascript" };
        IEnumerable<string> filteredNames = System.Linq.Enumerable.Where(names, n => n.Length >= 4);
        foreach (string n in filteredNames)
            Console.WriteLine(n);
    }
}
  

The output:


Java
Javascript

Because the standard query operators are implemented as extension methods, we can call Where directly on names-as though it were an instance method.

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        string[] names = { "C", "Java", "C#", "Javascript" };

        IEnumerable<string> filteredNames = names.Where(n => n.Length >= 4);

        foreach (string n in filteredNames)
            Console.WriteLine(n);
    }
}
  

The output:


Java
Javascript
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.