LINQ Interview questions and answers

LINQ

1)What is LINQ? 

-Linq is unified programming model
-Using Linq query able to retrive, insert , update and delete any kind of data from datasource 
-You can use any kind of data source (SQL, XML ,Objects, Collections, DataSet etc)

2)What is general syntax of LINQ query?

Every query starts with From clause ends with either select or group clause.

<<query_expression>> ::= from_clause query_body
<<query_body>> ::
(from_clause join_clause* | let_clause | where_clause)*
orderby_clause?
(select_clause | groupby_clause)
query_continuation?  (Example into keyword)

3)What is from clause in LINQ?

From clause is used to define datasource to the query or subquery.
A query can have multiple from clauses while joining different datasources.

4)What is where clause in LINQ?

Where is clause is used to filtered the datasource data with specified condition.
Query can have multiple where clauses

5)What is select clause in LINQ?

-Select clause projects the query results  into the enumerable object. 
-In VB select clause not mandatory

6)What is group clause in LINQ?

Group clause projects the query results into the set of groups depends on given key.

7)What is Let clause in LINQ?

Let clause is used hold the result of an expression into a variable, Use this results in entire application.

8)What is into clause in LINQ?

Into keyword is used conjunction with Group and select clauses but it is not mandatory.
We  use the into keyword to store the results of a select, group,or join statement in a temporary variable
this keyword is also called a continuation clause.

9)What is Order by clause in LINQ?

Using order by clause we can sort the result of the query either by ascending or descending.
We can combine one or more keys (keys means columns).
Default is ascending order.

using System;
using System.Linq;
using System.Collections;
public class Exercise1
{
    public static void Main( )
    {
        string[] mycolors = { "White", "block", "red", "blue" };
        var result = from mycolor in mycolors
                           orderby mycolor.Length
                            select mycolor;
        foreach(var item in result )
         System.Console.WriteLine(item);
    }
}

output

red
blue
White
block

10)What is joins clause in LINQ?

By using the join clause, you can define inner joins, group joins, and left outer joins

11)What is Join in LINQ?


-Only matching key elements are returned by this join clause from both outer and inner datasources
Skips all the not matching elements 
-It is like inner join in sql.
-It is return a flat result.

12)What is group join in LINQ?

Matching key elements from both data sources and not matching elements from outer data source are returned by this group  join clause.
It is not matching with any SQL joins
It is return  hierarchical result

13)What left outer join in LINQ?

It is same like group join only difference  is it return flat result rather than hierarchical result.

To produce this result need to use DefaultIfEmpty extension method.

14)What is Deferred Query Evaluation in LINQ?

A query is not evaluated when it is defined, but only evaluated when it is executed.

Because of this query always returns current items in a datasource , rather than compilation time items.

What is Immediate Execution in Linq?

When ever you use aggregate functions like Min, Max, Average..Etc. this will leads to execution of foreach statement implicitly but its only return integer value not IEnumerable collection.

15)what is difference between select and selectmany in LINQ?

if you have nested class and want to get flat result needs to use two foreach loops with select clause

class College
{
public Student[] Students{get;set;}
}

class Student 
{
public string Name {get;set;}
}
var colleges = new [] {
new College(){ Students = new [] { new Student(){ Name="Shiva"}, new Student(){ Name="Jai"} }},
new College(){ Students = new [] { new Student(){ Name="Gaurav"}, new Student(){ Name="Prame"} }}
};

var allStudents =colleges.Select(s=> s.Students);

foreach(var student in allStudents){
foreach(var std in student)
Console.WriteLine(std.Name);
}
o/p: Shiva
Jai
Gaurav
Pramee

if you use selectmany you will get the result with one foreach loop.

16)What is difference between OrderBy and OrderByDescending operators in LINQ?

Both are using for ordering results of the query.
OrderBy ordering the result items in ascending order.
OrderByDescending ordering the result items in descending order.

17)What is difference between ThenBy and ThenByDescending operators in LINQ?

When we want to order the data with many different keys then we use ThenBy and ThenByDescending.
Both are using for ordering results of the query.
ThenBy ordering the result items in ascending order.
ThenByDescending ordering the result items in descending order.
We use this both operators after using OrderBy and OrderByDescending 

18)What is Reverse operator in LINQ?

This operator is used to reverse the result of the query.  

syntax :

var sampleResult = colleges.Select(s=> s.Students).Reverse();

19)What is GroupBy operator in LINQ?

GroupBy operator also called grouping operator

it is used to grouping the elements based on key.

it provides great number of approx 8 overloads.

20)What is Distinct operator in LINQ?

if we want get unique results from  resultantset then use Distinct operator. 
(or)
if we want avoid dupicates from resultantset then use Distinct operator. 


21)What is Union operator in LINQ?

Union operator return  all the elements from the two sets without duplicates.
The Union operator go through the first set and the second set in that order and capture each element that has not already been captured.
Int32[] X = {11, 15, 16, 19};
Int32[] Y = {14, 15, 17, 11};
var union = X.Union(Y);

result = 11,15,16,19,14,17 

As union opeartaor working references of the elements some times you get dupicate results. so that needs bit careful.needs to use custom comparer.

if you want to avoid you can use value type Struct but inheritence is not possible with structs.

22)What is Intersect operator in LINQ?

Intersect operator captured  common elements from t the two sets.

Int32[] X = {11, 15, 16, 19};
Int32[] Y = {14, 15, 17, 11};
var union = X.Intersect(Y); 

result = 11,15

23)What is Except operator in LINQ?

Except operator capture all the elements from the first sequence that are not present in the second sequence.

Int32[] X = {11, 15, 16, 19};
Int32[] Y = {14, 15, 17, 11};
var union = X.Except(Y);
result = 16,19

24)What is ZIP operator in LINQ?

ZIP operator introduced in .NetFrmework 4.0.

ZIP operator maps each element in the first sequence to the element in the second sequence which is having the same index.

int[] num = { 1, 2, 3,4,5,6};
string[] words = { "one","two"};

var numWords = num.Zip(words, (first, second) => first + " " + second);

result:

1 one
2 two

25)What is the use of Count and LongCount operatos in C#.net?

you want to list all lecturers, each one followed by the number of degrees that lecturers has placed.

var expr = from l in lecturers
select new { l.Name, l.Country, DegreeCount = l.Degrees.Count() };

LongCount is returning long value rather than integer.

26)What is Sum, Min , Max , Average operators in LINQ?

Sum:is used to calculate arithmatic sum on set of values.
Average: is used to calculate arithmatic average on set of values.
Min:is used to get minimum  value from set of values.
Max:is used to get maximum value from set of values.

27)What is use of Aggregate operator in LINQ?

Operator perform an assembling.

int[] num = { 1, 2, 3,4,5,6};
var numWords = num.Aggregate((n1,n2) =>n1+n2); //op: 21

string[] word = { "1", "2","3","4","5","6"}; 
var numWords = word.Aggregate((n1,n2) =>n1+","+n2); //op: 1,2,3,4,5,6


28)What is Range operator in LINQ?

using this operator we can select integer numbers with in specified range.

29)What is Repeat operator in LINQ?

It returns the occurence of the element in specified number of times.

Student sobj= new Student();
sobj.Name = "Shiva";
var allStudents = Enumerable.Repeat((sobj.Name),3);

output:
Shiva
Shiva
Shiva

30)What is use of Empty operator in LINQ?

Empty operator is used to intialize the sequence with empty result.
IEnumerable<Student> Students = Enumerable.Empty<Student>();

31)What is Any operator in LINQ?

Any operator is used to check in a sequence for items using specified condition, whenever an item exists in the source sequence This returns true else return false

One more overload for checking at least one item exist in the sequence. if at least one item exist its return true.(like isempty method in strings) 

32)What is All operator in LINQ?

All operator is used to filter all the elements in the sequence with specified condition, if condition  is true for all then its return true otherwise return false.
All operator applied to empty sequence, It is always return true.

33)What is Contains operator in LINQ?

Contains operator is used to check weather specified element exist in the source or not. if exist return true if not return false;

using System;
using System.Linq;
using System.Collections;
public class Exercise1
{
    public static void Main( )
    {
        string[] mycolors = { "White", "block", "red", "blue" };
        var result = from mycolor in mycolors
                   where mycolor.Contains("o")
                   select mycolor;
        foreach(var item in result )
         System.Console.WriteLine(item);
    }
}

output

block

34)What is the difference between any and contains operators in LINQ?

Please read above two answers.

35)What is Take operator in LINQ?

Take operator is used to specify number elements you want to source or resultant value.

If resultant value is negative take returns an empty. 

if resultant value has the number elements smaller that take operator specified value , it returns all the elements.

int[] numbers = {1,2,3,4,5}; 
var allStudents = numbers.Take(3);
o/p: 
1,
2,
3

36)What is TakeWhile operator in LINQ?

TakeWhile operator alos working like Take but it evaluates the elements based on predicate. it iterate trhough the elements until return false or all the elements in the list


int[] numbers = {2,4,6,7,8}; 
var allStudents = numbers.TakeWhile(i=>i%2==0);

result: 
2,4,6 

37)What is Skip and SkipWhile operators in LINQ?

Skip and SkipWhile operators are compliment to the Take and TakeWhile operators.

38)What is First operator in LINQ?

Using First operator extracting first element in the sequence.
If element not present in the sequence First operator throw below exception.
[System.InvalidOperationException: Sequence contains no elements]


39)What is FirstOrDefault operator in LINQ?

It is also working like a First operator, difference is not throwing any exception if element not exist, it returns defualt value in that case.

40)What is Last and LastOrDefault operators in LINQ?

These operators are opposite to First , FirstOrDefaut.


For Part-2   click here

Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment