Select operation using LINQ

As we have seen before , we can perform a lot of sql like operations using LINQ, here i will explain you about how we can perform the select operation using LINQ

This program will have a list of integers with 10 integers added into the list from 1 to 10
we can perform the basic select operations on this list by using LINQ

Please import the System.Linq namespace else you may not be able to use this program.

------------------------------ the code-------------------------------------

using System;
using System.Collections.Generic;
using System.Linq; 
using System.Text;


namespace caLinqSelect
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>();
            intList.Add(1);
            intList.Add(2);
            intList.Add(3);
            intList.Add(4);
            intList.Add(5);
            intList.Add(6);
            intList.Add(7);
            intList.Add(8);
            intList.Add(9);
            intList.Add(10);


            IEnumerable<int> queryResult = from myInts in intList where myInts > 5 select myInts;


            foreach (int i in queryResult)
            {
                Console.WriteLine(i);
            }


            Console.ReadKey();
        }
    }
}
-------------------------------------------------------------------------------

The program
This program has a list of integers called intList , there are few integers loaded into the list (1,2,3 ...10).
The program has something called IEnumerable, yes you have guessed it right, its an interface that exposes the enumerator, which supports a simple iteration over a non-generic collection.in our case its  int , but that's not the main concern here.
Next, we have the query, " from myInts in intList where myInts > 5 select myInts" now what does this do? this will select all the integers from the list intList whose value is greater than 5 and store it into the   IEnumerable<int> queryResult  
Now we have a new resultset which has the integers that have values greater than 5. we can easily iterate over this resultset to do what ever operation we want to.


















The O/P:    6,7,8,9,10













we can use any type of operator to perform the filtering of the select. like <, > ,== ,!= etc 
you can download the solution files from here  or copy paste this URL into your browser (https://www.box.com/s/8f20dc961cc2893b9fdf)

Thanks for reading the post, Please comment if you find it difficult to understand or if you have any queries..

No comments:

Post a Comment