Introduction to LINQ Queries

Category: System.Linq, viewed: 155 time(s).

LINQ (Language Integrated Query) is a language feature that allows a common way to access or query different type of data sources. In the previous technology we might have seen many query languages such as SQL for relational database, XQuery for XML data, etc.

LINQ on the other hand offers developer a consistent model for working across various kind of data sources. We can use LINQ to work with objects, array, file system, accessing SQL databases, XML documents, .NET collections, ADO.NET databases.

As long as a LINQ provider available for a certain type of data then we can use a LINQ query to work with that data source.

Here is an example on how to LINQ simplify a program for accessing even and odd numbers from an array of integer.

using System;
using System.Linq;

namespace Kodecsharp.Example.Linq
{
    class LinqIntro
    {
        [STAThread]
        public static void Main(string[] args)
        {
            int[] numbers = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

            var evenNumbers =
                from number in numbers
                where (number % 2) == 0
                select number;

            Console.WriteLine("Even numbers: ");
            foreach (int number in evenNumbers)
            {
                Console.Write(number + " ");
            }

            var oddNumbers =
                from number in numbers
                where (number % 2) != 0
                select number;

            Console.WriteLine("");
            Console.WriteLine("Odd numbers: ");
            foreach (int number in oddNumbers)
            {
                Console.Write(number + " ");
            }

            Console.ReadLine();
        }
    }
}

The program above will print out the following results:

Even numbers:
2 4 6 8 10
Odd numbers:
1 3 5 7 9
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page