Top 10 LINQ Interview Questions and Answers

1) What is a Lambda expression?

A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.

Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.



Example :

               int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };  
               int oddNumbers = numbers.Count(n => n % 2 == 1); 


2) Explain what is LINQ? Why is it required?

Language Integrated Query or LINQ is the collection of standard query operators which provides query facilities into.NET framework language like C#, VB.NET.

LINQ is required as it bridges the gap between the world of data and world of objects.

3) What are the types of LINQ?

  i )  LINQ to Objects
  ii )  LINQ to XML
  iii ) LINQ to Dataset
  iv ) LINQ to SQL
  v  ) LINQ to Entities

4) Define what is Where clause and Let clause?

Where clause: It allows adding some conditional filters to the query.
Let clause: It allows defining a variable and assigning it a value calculated from the data values.

5) In LINQ how will you find the index of the element using where () with Lambda Expressions?

In order to find the index of the element using where () with the lambda expression

Where ( ( i, ix ) => i == ix);

6) Difference Between First() and FirstOrDefault() in LINQ

IDNameYearAddressIncomeUserName
1Sandeep2010-2011Bangalore50000S123
2Rakhi2012-2013Hyderabad180000S123
3Reena 2013-2014Pune200000S789
4Priya2013-2014Ranchi350000S253

A. First()

When we Use First() in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Expression in Where Clause then It Will Throw You Exception as: InvalidOperationException: Sequence contains no elements.

var x =(from m in Member  where m.UserName=’S000’  select m.Name,m.Income,m.Year ).First()  

When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().

B. FirstORDefault()

When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null).


FirstOrDefault () returns First Element Of Sequence.

FirstOrDefault () does not throws Exception when There IS No element Present in Table.

7) Compare two list and remove duplicates in c# using linq

        var list1 = new List<DownloadTask>();
        list1.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 2, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 3, MachineID = 1 });
        list1.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });

        var list2 = new List<DownloadTask>();
        list2.Add(new DownloadTask{ OperationID = 1, MachineID = 1 });

        list2.Add(new DownloadTask{ OperationID = 3, MachineID = 2 });

var lst = (from lst1 in list1 here !list2.Any(
                       x => x.OperationID == lst1.OperationID && 
                       x.MachineID == lst1.MachineID )
                       select lst1).ToList();


     list1 = lst.ToList(); 

8) How to use the GroupBy in LINQ 

The ‘GroupBy’ feature in LINQ is amazing and very powerful. When you use a ‘GroupBy’ in LINQ, internally, it calls an extension method which returns a sequence of System.Collections.Generic.IEnumerable<(Of <(IGrouping<(Of <(TKey, TSource>)>)>)>).

empList.Add(new Employee() { ID = 1, FName = "John", MName = "", LName = "Shields", 
DOB = DateTime.Parse("12/11/1971"), Sex = 'M' }); 

empList.Add(new Employee() { ID = 2, FName = "Mary",  MName = "Matthew", 
                      LName = "Jacobs", DOB = DateTime.Parse("01/17/1961"), Sex = 'F' }); 

empList.Add(new Employee() { ID = 3, FName = "Amber",  MName = "Carl",
                     LName = "Agar", DOB = DateTime.Parse("12/23/1971"), Sex = 'M' }); 

empList.Add(new Employee() { ID = 4, FName = "Kathy", MName = "", LName = "Berry", 
DOB = DateTime.Parse("11/15/1976"), Sex = 'F' }); 

empList.Add(new Employee() { ID = 5, FName = "Lena",  MName = "Ashco",
                          LName = "Bilton",  DOB = DateTime.Parse("05/11/1978"), Sex = 'F' })


Example 1  
List of employees grouped by the first letter of their first name
To display a list of employees group by the first alphabet of their first name, use this query:

var grpOrderedFirstLetter = empList.GroupBy(employees => 
    new String(employees.FName[0], 1)).OrderBy(employees => 
    employees.Key.ToString());

Example 2
List of employees grouped by the year in which they were born
In order to group the employees based on the year in which they were born, use this query:
         
var grpOrderedYr = empList.GroupBy(employees => 
    employees.DOB.Year).OrderBy(employees => employees.Key); 

Example 3

Sex ratio
To find the sex ratio in the company, use this query:

var ratioSex = empList.GroupBy(ra => ra.Sex) 
  .Select( emp => new 
  { 
      Sex = emp.Key, 
      Ratio = (emp.Count() * 100) / empList.Count 

  }); 

Share this

Previous
Next Post »