Introduction to LINQ

LINQ stands for language integrated query. LINQ is a .NET alternative to SQL. LINQ is designed for those .NET developers who don’t find themselves comfortable with SQL. A LINQ query operates over some data. This data consists of two parts: A sequence that must implement the IEnumerable interface and some items. For instance an array is a collection that implements IEnumerable interface and contains some item. Consider the following code.

  // An array sequence with some items
            string[] cars = { "Toyota", "Ford", "BMW", "Honda" };

In the above code, the array “cars” is a sequence while string type elements “Toyota”, “Ford” etc are the items.

Linq contains query operators that are basically static extension method of the Enumerable class of the System.Linq namespace. There are around 40 query operators in this class. A query operator is used to act on a LINQ data sequence and produce another sequence. The cars sequence is a local sequence i.e. this sequence exits in the memory of the computer. The LINQ queries that operate on local type of sequence are called local queries. LINQ queries can also operate on remote data such as SQL databases and XML files.

A query expression in LINQ consists of an operator and a sequence on which the operator acts and yield some results. A simplest query expression consists of one sequence and one query operator. Have a look at the following example to see how we can retrieve name of all the cars that doesn’t contain letter ‘o’ in their names.

´╗┐using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            // An array sequence with some items
            string[] cars = { "Toyota", "Ford", "BMW", "Honda" };

            // Linq query to find cars with no letter o in it
            IEnumerable<string> cars2 = cars.Where(c => !c.Contains("o"));
            foreach (string c in cars2) Console.WriteLine(c);

Download the code

In the above code, “where” query operator is being used to check whether the item in the cars array contains the letter ‘o’ in it or not. If the item doesnt contain o, it is added in the output sequence, else it is filtered. Once the operator has iterated over each item, the output sequence is returned. In cars array, only “BMW” was the item which did not contain ‘o’, therefore this item will be returned and displayed on the output.

<<< File Reading and Writing in C#LINQ Fluent vs Query Syntax >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .