Linq

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday 31 August 2016

Linq Query Can be Executed More than once

A linq Query can be executed more than once.

Source Code
using System.Linq;  
 using System;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       int[] number = { 101, 102, 103, 104, 105 };  
       var final = from num in number  
             where num > 102  
             select num;  
       foreach (var item in final)  
       {  
         Console.WriteLine(item);  
       }  
       number[1] = 200;  
       Console.WriteLine("----after---");  
       foreach (var item in final)  
       {  
         Console.WriteLine(item);  
       }  
       Console.ReadLine();  
     }  
   }  
 }  

Output










Debugging











Monday 11 July 2016

Linq :- Some of the handy statements

  • These are some of the common interview question asked.
1)Remove Duplicates from a list
using System.Linq;  
 using System;  
 using System.Collections.Generic;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       List<string> list = new List<string>() { "anurag","anurag","abc","abc","xyz"};  
       Console.WriteLine("::Duplicate Strings in a List::");  
       var duplicateString = list.GroupBy(x => x)  
             .Where(group => group.Count() > 1)  
             .Select(group => group.Key);  
       foreach (var item in duplicateString)  
       {  
         Console.WriteLine(item);  
       }  
       Console.ReadLine();  
     }  
   }  
 }  


2)Remove duplicates in a given string
using System.Linq;  
 using System;  
 using System.Collections.Generic;  
 using System.Text.RegularExpressions;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       string input = "anurag;anurag;anurag2;anurag3;anurag4";  
       string output = string.Join(";", input.Split(';').Distinct().ToArray());  
       Console.WriteLine(output);  
       Console.ReadLine();  
     }  
   }  
 }  


3)Finding Smallest String
 using System.Linq;  
 using System;  
 using System.Collections.Generic;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       List<string> list = new List<string>() { "anurag","abhishek","xyz"};  
       Console.Write("Small String-> ");  
       Console.WriteLine(list.OrderByDescending(x => x.Length).Last());  
       Console.ReadLine();  
     }  
   }  
 }  






4)Remove duplicate characters of a string
using System.Linq;  
 using System;  
 using System.Collections.Generic;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       string s = "Dddduppplicaaate";   
       Console.Write("Removed Duplicate Characters -> ");  
       Console.WriteLine(new string(s.ToLower().ToCharArray().Distinct().ToArray()));  
       Console.ReadLine();  
     }  
   }  
 }  







5)Occurrences of string
 using System.Linq;  
 using System;  
 using System.Collections.Generic;  
 using System.Text.RegularExpressions;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       string s = "This is great.But is this really great ??";  
       Console.Write("String Occurences(this) -> ");  
       Console.WriteLine(Regex.Matches(s, "this", RegexOptions.IgnoreCase).Count);  
       Console.ReadLine();  
     }  
   }  
 } 







True For All and ALL(Check if all values are same)

using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace LINQ  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       List<int> num1 = new List<int> { 2, 2, 2, 2 };  
       bool evenOrOdd = num1.TrueForAll(x => x == 2);  
       Console.WriteLine(evenOrOdd);  
       Console.ReadLine();  
     }  
   }  
 } 

Output









This gives the Same output:

 bool evenOrOdd= num1.All(x=>x==2);

Will update more on this post :)












Sunday 26 June 2016

Interview Question:- How to use left join in Linq ?

Scenario

  • List of Employee. 
  • List of Departments.
  • Each Employee belongs to Particular department
  • There are some Employees which belongs to some departments which are not there in the department list.
  • Need all the Employees and the department name. Mark 'No Department' for those employees whose departmentId doesn't match with department list.


Code
 using System;    
  using System.Collections.Generic;    
  using System.Linq;    
  using System.Text;    
  namespace GroupJoin    
  {    
  class Program    
  {    
   public static void Main()    
   {    
   List<Employee> objEmployeelist =  new List<Employee>        
    {        
    new Employee{ EmployeeID=1, EmployeeName ="Anurag", DepID=1},    
    new Employee{ EmployeeID=2, EmployeeName ="Abhishek",DepID=2},    
    new Employee{ EmployeeID=4, EmployeeName ="Ayush", DepID=1},    
    new Employee{ EmployeeID=3, EmployeeName ="Rahul", DepID=6}    
    };    
     List<Department> objDepartmentlist = new List<Department>     
    {    
    new Department {DepartmentID=1,DepartmentName="HR"},    
    new Department {DepartmentID=2,DepartmentName="Admin"},    
    new Department {DepartmentID=3,DepartmentName="Lib"},    
    new Department {DepartmentID=4,DepartmentName="Abc"}    
    };    
     var list = (from e in objEmployeelist    
     join d in objDepartmentlist    
     on e.DepID equals d.DepartmentID into ds    
     from d in ds.DefaultIfEmpty()    
     select new { emp = e, dep=(d==null ?"No Department":d.DepartmentName) }).ToList();    
    // loop over here == null ? "(No products)" : p.ProductName    
    foreach (var item in list)    
    {    
    Console.WriteLine(item.emp.EmployeeName + "::" + item.dep);    
    }    
    Console.ReadLine();    
   }    
   }    
   public class Employee    
   {    
   public int EmployeeID;    
   public string EmployeeName;    
   public int DepID;    
   }    
   public class Department    
   {    
   public int DepartmentID;    
   public string DepartmentName;    
   }    
  }    

Output


Saturday 14 May 2016

Inner Join linq c#


Inner Join using Lambda Expression and Linq

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace GroupJoin  
 {  
   class Program  
   {  
     public static void Main()  
     {  
       List<Employee> objEmployeelist =  
       new List<Employee>   
       {                  
       new Employee{ EmployeeID=1, EmployeeName ="Anurag", DepID=1},              
       new Employee{ EmployeeID=2, EmployeeName ="Abhishek",DepID=2},                  
       new Employee{ EmployeeID=3, EmployeeName ="Rahul", DepID=6}  
       };  
       List<Department> objDepartmentlist = new List<Department>  
       {  
        new Department {DepartmentID=1,DepartmentName="HR"},  
        new Department {DepartmentID=2,DepartmentName="Admin"},  
        new Department {DepartmentID=3,DepartmentName="Lib"},  
        new Department {DepartmentID=4,DepartmentName="Abc"}  
       };  
       var listlinq = from e in objEmployeelist  
               join d in objDepartmentlist  
               on e.DepID equals d.DepartmentID  
               select new { emp = e, dep = d };  
       var listlambda = objEmployeelist.Join(objDepartmentlist, e => e.DepID, d => d.DepartmentID,  
         (e, d) => new { emp = e, dep = d });  
       foreach (var item in listlambda)  
       {  
         Console.WriteLine(item.emp.EmployeeName + "::" + item.dep.DepartmentName);  
       }  
       Console.ReadLine();  
     }  
   }  
   public class Employee  
   {  
     public int EmployeeID;  
     public string EmployeeName;  
     public int DepID;  
   }  
   public class Department  
   {  
     public int DepartmentID;  
     public string DepartmentName;  
   }  
 }  









Sunday 13 September 2015

SelectMany In Linq c#


SelectMany

  • Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.
  • Projection Operator like Select
  • When we nested list, SelectMany becomes useful. We need only one loop using selectMany to traverse elements of the nested list.
Scenario
  • List of students and have list of subjects in it.
  • Find out the subjects which Mike is enrolled to ?
Code
using System;  
 using System.Collections.Generic;  
 using System.Globalization;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace ConsoleApplication1  
 {  
   class Program  
   {  
     class SoftwareStudent  
     {  
       public string Name { get; set; }  
       public string RollNumber { get; set; }  
       public List<string> Subject { get; set; }  
     }  
     static void Main(string[] args)  
     {  
       List<SoftwareStudent> students = new List<SoftwareStudent>{  
                    new SoftwareStudent {  
                      Name = "Anurag",  
                      RollNumber ="1" ,  
                      Subject= new List<string>{"Dotnet","Java","Informatica"}},  
                    new SoftwareStudent {  
                      Name = "Abhishek",  
                      RollNumber ="2" ,  
                      Subject= new List<string>{"Che","Phy"}},  
                    new SoftwareStudent {  
                      Name = "Mike",  
                      RollNumber ="3" ,  
                      Subject= new List<string>{"Dotnet","php","BigData"}}};  
       var result4 = students.Where(x => x.Name == "Mike").ToList();  
       string subjectMike=string.Empty;  
       foreach (var item in result4)  
       {  
         var count = item.Subject.Count;  
         foreach (var item1 in item.Subject)  
         {  
           subjectMike += item1 + ";";  
           if (--count <= 0)  
           {  
             subjectMike = subjectMike.TrimEnd(';');//Dotnet;php;BigData  
           }   
         }  
       }  
        Console.WriteLine(subjectMike);  
        //*******************SELECT MANY*****************//  
       string subjectMike1 = string.Empty;  
       var MikeSubSelMany = students.Where(x => x.Name == "Mike").SelectMany(student => student.Subject, (st1, subject) => new { st1.RollNumber,st1.Name, subject });  
       //var MikeSubSelMany1 = students.Where(x => x.Name == "Mike").SelectMany(student => student.Subject);  
       var count2 = MikeSubSelMany.Count();  
       foreach (var item2 in MikeSubSelMany)  
       {  
         subjectMike1 += item2.subject + ";";  
         if (--count2 <= 0)  
         {  
           subjectMike1 = subjectMike.TrimEnd(';');//Dotnet;php;BigData  
         }   
       }  
       Console.WriteLine(subjectMike1);  
       Console.ReadLine();  
     }  
   }  
 }  


So highlighted is the use of selectmany. You only need to loop once to get the results of the subjects taken by mike.

This Piece of code also produces the same result.

Using overloaded version of SelectMany

 var MikeSubSelMany = students.Where(x => x.Name == "Mike").  
       SelectMany(student => student.Subject);   
     //var MikeSubSelMany1 = students.Where(x => x.Name == "Mike").SelectMany(student => student.Subject);   
     var count2 = MikeSubSelMany.Count();   
     foreach (var item2 in MikeSubSelMany)   
     {   
      subjectMike1 += item2 + ";";   
      if (--count2 <= 0)   
      {   
       subjectMike1 = subjectMike.TrimEnd(';');//Dotnet;php;BigData   
      }    
     }   
     Console.WriteLine(subjectMike1);   
     Console.ReadLine(); 


Debugging


O/P with with both SelectMany and without Selectmany gives same result







Tuesday 16 December 2014

GroupBy & Join Linq C#

Group By Linq
  • powerful feature of linq Similar to Group by as SQL
  • It can be done using both linq as well as lambda expression.
Code
using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace XML  
 {  
   class Program  
   {  
     public class student  
     {  
       public int id { get; set; }  
       public string name { get; set; }  
       public int classId { get; set; }  
       public List<student> getStudents()  
       {  
         List<student> obj = new List<student>();  
         obj.Add(new student { id = 101, name = "abc1", classId = 1 });  
         obj.Add(new student { id = 102, name = "abc2", classId = 1 });  
         obj.Add(new student { id = 103, name = "abc3", classId = 2 });  
         obj.Add(new student { id = 104, name = "abc4", classId = 2 });  
         obj.Add(new student { id = 105, name = "abc5", classId = 2 });  
         obj.Add(new student { id = 106, name = "abc6", classId = 3 });  
         obj.Add(new student { id = 107, name = "abc7", classId = 3 });  
         obj.Add(new student { id = 108, name = "abc8", classId = 3 });  
         obj.Add(new student { id = 109, name = "abc9", classId = 3 });  
         return obj;  
       }  
     }  
     static void Main(string[] args)  
     {  
       student s = new student();  
       var students = s.getStudents().ToList();  
       var final = students.GroupBy(x => x.classId).ToDictionary(y => y.Key, y => y.ToList());  
       foreach (var x in final)  
       {  
         Console.WriteLine("----" + x.Key + "-----");  
         foreach (var item in x.Value)  
         {  
           Console.WriteLine(item.id);  
           Console.WriteLine(item.name);  
           Console.WriteLine();  
         }  
         Console.WriteLine("===================================");  
       }  
       Console.WriteLine("--------Slight Modification----------");  
       var final1 = students.GroupBy(x => x.classId).Select(g => new { Key=g.Key, List=g.ToList() });  
       foreach (var item in final1)  
       {  
         Console.WriteLine("----" + item.Key + "-----");  
         foreach (var item1 in item.List)  
         {  
           Console.WriteLine(item1.id);  
           Console.WriteLine(item1.name);  
           Console.WriteLine();  
         }  
       }  
       Console.ReadLine();  
     }  
   }  
 }  

Both Gives Same result: 



























Group By and Sum

Code
using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace LINQ  
 {  
   class Program  
   {  
     public class student  
     {  
       public int id { get; set; }  
       public string name { get; set; }  
       public int classId { get; set; }  
       public int Salary { get; set; }  
       public List<student> getStudents()  
       {  
         List<student> obj = new List<student>();  
         obj.Add(new student { id = 101, name = "abc1", classId = 1, Salary = 100 });  
         obj.Add(new student { id = 102, name = "abc2", classId = 1, Salary = 200 });  
         obj.Add(new student { id = 103, name = "abc3", classId = 2, Salary = 300 });  
         obj.Add(new student { id = 104, name = "abc4", classId = 2, Salary = 800 });  
         obj.Add(new student { id = 105, name = "abc5", classId = 2, Salary = 900 });  
         obj.Add(new student { id = 106, name = "abc6", classId = 3, Salary = 250 });  
         obj.Add(new student { id = 107, name = "abc7", classId = 3, Salary = 260 });  
         obj.Add(new student { id = 108, name = "abc8", classId = 3, Salary = 290 });  
         return obj;  
       }  
     }  
     static void Main(string[] args)  
     {  
       student s = new student();  
       var students = s.getStudents().ToList();  
       var z = students.GroupBy(x => x.classId).Select(g => new {ClassId=g.Key, TotalSalary= g.Sum(x=>x.Salary) });  
       foreach (var item in z)  
       {  
         Console.WriteLine(item.ClassId);  
         Console.WriteLine(item.TotalSalary);  
         Console.WriteLine();  
       }  
       Console.ReadLine();  
     }  
   }  
 }  


O/P:
















using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace LINQ  
 {  
   class Program  
   {  
     class Parent  
     {  
       public int Id { get; set; }  
       public string Val { get; set; }  
     }  
     class Child  
     {  
       public int Id { get; set; }  
       public string ChildVal { get; set; }  
     }  
     static void Main(string[] args)  
     {  
       List<Parent> plist = new List<Parent>() {  
         new Parent{ Id=1, Val="X"},  
         new Parent{ Id=2, Val="Y"},  
         new Parent{ Id=3, Val="Z"}  
       };  
       List<Child> clist = new List<Child>() {  
         new Child{ Id=1, ChildVal="X1"},  
         new Child{ Id=1, ChildVal="X2"},  
         new Child{ Id=1, ChildVal="X3"},  
         new Child{ Id=2, ChildVal="Y1"},  
         new Child{ Id=2, ChildVal="Y2"},  
         new Child{ Id=4, ChildVal="Y3"},  
       };  
       var joinedResult = from p in plist  
                 join c in clist on p.Id equals c.Id  
             select new { p.Val, c.ChildVal };  
       Console.WriteLine("===JOIN===");  
       foreach (var item in joinedResult)  
       {  
         Console.WriteLine(item.Val);  
         Console.WriteLine(item.ChildVal);  
         Console.WriteLine();  
       }  
       Console.WriteLine("===GROUPJOIN===");  
       var y = from p in plist  
           join c in clist on p.Id equals c.Id into g  
           select new { Parent = p, Children = g };  
       foreach (var item in y)  
       {  
         Console.WriteLine(item.Parent.Id);  
         foreach (var item1 in item.Children)  
         {  
           Console.WriteLine(item1.ChildVal);  
         }  
         Console.WriteLine();  
       }  
       Console.ReadLine();  
     }  
   }  
 }  



Second Highest Salary using LINQ

Topic

Finding the Second Highest or nth highest using Linq

Scenario

  • List of Students. Each having name,Salary etc
  • Find the second highest or nth highest salary
Code

using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace XML  
 {  
   class Program  
   {  
     public class student  
     {  
       public int id { get; set; }  
       public string name { get; set; }  
       public int classId { get; set; }  
       public int Salary { get; set; }  
       public List<student> getStudents()  
       {  
         List<student> obj = new List<student>();  
         obj.Add(new student { id = 101, name = "abc1", classId = 1, Salary = 100 });  
         obj.Add(new student { id = 102, name = "abc2", classId = 1, Salary = 200 });  
         obj.Add(new student { id = 103, name = "abc3", classId = 2, Salary = 300 });  
         obj.Add(new student { id = 104, name = "abc4", classId = 2, Salary = 800 });  
         obj.Add(new student { id = 105, name = "abc5", classId = 2, Salary = 900 });  
         obj.Add(new student { id = 106, name = "abc6", classId = 3, Salary = 250 });  
         obj.Add(new student { id = 107, name = "abc7", classId = 3, Salary = 260 });  
         obj.Add(new student { id = 108, name = "abc8", classId = 3, Salary = 290 });  
         return obj;  
       }  
     }  
     static void Main(string[] args)  
     {  
       student s = new student();  
       var students = s.getStudents().ToList();  
       var firsthighest = students.OrderByDescending(x => x.Salary).Select(x => x.Salary).First();  
       var secondhighest = students.OrderByDescending(x => x.Salary).Where(x => x.Salary != firsthighest).Select(x => x.Salary).First();  
       var secondhighest1 = students.OrderByDescending(x => x.Salary).Skip(2).Select(x => x.Salary).First();  
       var secondhighest2 = students.Where(x => x.Salary != (students.Max(x1 => x1.Salary))).Select(x => x.Salary).Max();  
       Console.WriteLine(secondhighest1);  
       Console.WriteLine(secondhighest2);  
       Console.ReadLine();  
     }  
   }  
 }  


Output