Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Sunday, August 25, 2013

Linq - Parallel Query and Cross Apply


In this article we are going to see how to create a parallel query execution and how to do the cross apply in Linq.

Parallel Query Execution :

/* Generate Even Numbers using parallel Extension. Execution of query in parallel to generate the Even number */
You can see the output of this program that the even numbers are print in UnOrder manner due to the parallel execution of query.

IEnumerable<int> values = ParallelEnumerable.Range(1, 40).Where(x => x % 2 == 0);
foreach (int i in values)
   Console.WriteLine(i);

Output:
2
4
22
32
6
12
24
34
8
14
26
36
10
16
28
38
18
30
40
20

Cross Apply:
Some times we have a requirement that cross apply the collection and get the value in another collection.
this can be done by SelectMany of one collection for each value of select in another collection.


  /* Cross Apply in Linq */
  var list1 = new List<string>() { "PC", "LAP", "TAB"};
  var list2 = new List<string>() { "HomeTheatre", "Graphics Card", "Moderm" };

  var cross = list1.SelectMany(x => list2.Select(y => x + "+"+ y));
   foreach (string crs in cross)
        Console.WriteLine(crs);


Output:

PC+HomeTheatre
PC+Graphics Card
PC+Moderm
LAP+HomeTheatre
LAP+Graphics Card
LAP+Moderm
TAB+HomeTheatre
TAB+Graphics Card

TAB+Moderm


From this article I hope that you can learn the some basics parallel query execution and how to do the cross apply of Linq.

LINQ - usage of SequenceEqual method



In this article we are going to the usage of SequenceEqual method. Let we see the example how it is works.


            /*Find the equal of two sequence */
            varseq1 = new List<int>() {1,6,3,21};
            varseq2 = new List<int>() {4,6,21,3,5};
            varseq3 = new List<int>() { 3, 6, 21, 1 };
            varseq4 = new List<int>() { 1, 6, 3, 21 };


            Console.WriteLine(seq1.SequenceEqual(seq2));
Output:
     False

The output for the above code is false, because the values present in seq1 and seq2 is different.



            Console.WriteLine(seq1.SequenceEqual(seq3));  
Output:
      False

The output for the above code is false, because the values present in seq1 and seq3 is same but are in different sequence.

         

            Console.WriteLine(seq1.SequenceEqual(seq4));
Output:
       True

The output for the above code is True, because the values present in seq1 and seq4 is same and also in sequence.

From this article you can learn the usage of SequenceEqual in Linq.

Linq - Find the size of a Directory


In this article we are going to see the usage of EnumerateFiles and EnumerateDirectories in Linq and how it is working.

EnumerateFiles() : Will enumerate the files present in the folder 
EnumerateDirectories() : Will enumerate the Directory present in the folder.

/* Directory Size*/
   long_size = Size(@"D:\flot", true);
   Console.WriteLine("Directory Size in MB : {0:N2} MB", ((double)_size) / (1024 * 1024));
          

   static long Size(stringpath, bool includesubdir)
   {
            DirectoryInfoinfo = new DirectoryInfo(path);

            long_size = info.EnumerateFiles().Sum(x => x.Length);

            if(includesubdir)
            _size+=info.EnumerateDirectories().Sum(x => Size(x.FullName,includesubdir));
           
            return_size;
    }



Output :

Directory Size in MB : 2.14 MB

LINQ - Usage of Convert All Method



In this article we are going to see a usage of convert all method. If we want to convert the data type of values present in the collection then we can do it through ConvertAll.



/* Convert All method */
   varresults = new List<object>() { 1, 0, 1, 1, 0, "true" };
   List<bool> boolresults = results.ConvertAll(x => Convert.ToBoolean(x));
   foreach(bool res inboolresults)
             Console.WriteLine(res);



In this example we have a list of values which are in object type , so we are converting all to the boolean type. Now the value 1 and "true" are cast as Bool True. and 0 as False.

Output:

True
False
True
True
False
True

I hope from this you can understand the usage of ConvertAll() method.

Linq - Usage of Union method


In this article we are going to see the usage of union method in Linq, It is same as Union the two collection sets.

For Example 
consider a collection seq1 which have numbers 1,6,3,21
consider a collection seq2 which have numbers 4,6,21,3,5

By union this two collection output is 1,6,3,21,4,5. How we can achieve this using Linq.

var seq1 = new List<int>() {1,6,3,21};

varseq2 = new List<int>() {4,6,21,3,5};

/*union of two sequence */
vardiff=seq1.Union(seq2);
foreach(int d in diff)
     Console.WriteLine(d);


Output :
1
6
3
21
4
5

From this article you can learn the usage of Union in Linq.

LINQ - usage of Except method in Linq

In this post let we see the difference between the collections , using Linq. Let we take a two examples first is compare with collection then with collection two.

var seq1 = new List<int>() {1,6,3,21};
var seq2 = new List<int>() {4,6,21,3};


Now let take a example of two collections, following example is used to find the values of collection seq1 which is not present in collection seq2.

/*Difference between two sequence */
   vardiff=seq1.Except(seq2);

    foreach (int d in diff)
       Console.WriteLine(d);

Output : 

1

Now let take a example of two collections, following example is used to find the values of collection seq2 which is not present in collection seq1.

/*Difference between two sequence */
   var diff=seq2.Except(seq1);

    foreach (int d in diff)
       Console.WriteLine(d);

Output : 

4



From this article i hope you can understand how to get the difference between the collections.

Sunday, July 14, 2013

LINQ - Select the required data from collection





























                                                                                                                                                                     
As the Dot Net have more techniques to iterate and fetch the data from collection, One of the best thing is LINQ. Linq is used in Objects, XML, Dataset etc.

Now, we are going to see a Linq sample Which will select the records from Collection of custom template.

In this Example we will create a Employee class with some property [Name,Age,Sex,Country, Phone Number],Based on that class create a employee collection .

    enum Gender
    {
        Male,
        Female
    }

    class Employee
    {
        public string Name { set; get; }

        public string Country { set; get; }

        public Gender Sex { set; get; }

        public int Age { set; get; }

        public int PhoneNo { set; get; }

    }


Select the employees who are male
      




















class Program
    {
        static List GetEmployeeCollection()
        {
            List _emp = new List();
            _emp.Add(new Employee() 
                    { 
                        Name = "Stepen", 
                        Age = 31, 
                        Sex=Gender.Male, 
                        Country = "US", 
                        PhoneNo = 2341094 
                    });

            _emp.Add(new Employee() 
                    { 
                        Name = "Daniel", 
                        Age = 21,
                        Sex=Gender.Male, 
                        Country = "US",
                        PhoneNo  = 4563234 
                    });

            _emp.Add(new Employee() 
                    { 
                        Name = "Suresh", 
                        Age = 22,
                        Sex = Gender.Male, 
                        Country = "INDIA", 
                        PhoneNo = 8574094 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Indhu", 
                        Age = 35, 
                        Sex = Gender.Female, 
                        Country = "INDIA", 
                        PhoneNo = 23417546 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Vinay", 
                        Age = 41, 
                        Sex = Gender.Male, 
                        Country = "UK", 
                        PhoneNo = 23456788 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Sundar", 
                        Age = 21, 
                        Sex = Gender.Male, 
                        Country = "UK", 
                        PhoneNo = 33425673 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Mark", 
                        Age = 36, 
                        Sex = Gender.Male, 
                        Country = "INDIA", 
                        PhoneNo = 88765456 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Alex", 
                        Age = 26, 
                        Sex = Gender.Male, 
                        Country = "US", 
                        PhoneNo = 88764546 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Maria", 
                        Age = 27, 
                        Sex = Gender.Male,
                        Country = "JAPAN", 
                        PhoneNo = 33245433 
                    });
            return _emp;
        }

        static void Main(string[] args)
        {   
            /* print  the employees information who are male  */
            foreach (Employee emp in GetEmployeeCollection().
                                                         Where(x => x.Sex == Gender.Male))
            {
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2},\tcountry {3}", emp.Name, 
                                                          emp.Age, emp.Sex, emp.Country);
            }

            Console.Read();
        }

    }

Output















 Select the employees who are born in "US"

/* print  the employees information who are in Country "US"  */
            foreach (Employee emp in GetEmployeeCollection().Where(x => x.Country == "US"))
            {
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2},\tcountry {3}", 
                                                emp .Name, emp .Age, emp .Sex, emp .Country);

            }

Output :





Select All Emplloyees who are the age above 26 in India

 /* print  the employees who are in Country "India" and age is greater than 26   */
            foreach (Employee emp in GetEmployeeCollection().Where(x => x.Country == "INDIA"  &&                                                                                                                 x.Age > 26 ))
            {
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2},\tcountry {3}", 
                                                emp .Name, emp .Age, emp .Sex, emp .Country);

            }

Output 


Group the employees based on the Country

 /* print  the employees information who are in Country "US"  */
             foreach (var empgrp  in GetEmployeeCollection().GroupBy(x=>x.Country).Select(x=>new                                                                                                                                              {x.Key,x}))
            {
                Console.WriteLine("Country {0}", empgrp.Key);
                foreach(Employee emp in empgrp.x)
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2}", emp.Name, emp.Age,                                                               emp.Sex);
                Console.WriteLine();
            }

            Console.Read();



Output

Country US Employee Name Stepen, Age 31, Sex Male Employee Name Daniel, Age 21, Sex Male Employee Name Alex, Age 26, Sex Male Country INDIA Employee Name Suresh, Age 22, Sex Male Employee Name Indhu, Age 35, Sex Female Employee Name Mark, Age 36, Sex Male Country UK Employee Name Vinay, Age 41, Sex Male Employee Name Sundar, Age 21, Sex Male Country JAPAN Employee Name Maria, Age 27, Sex Male