LINQ Interview Questions and Answers (70) - Page 2

What is LINQ?

NOTE: This is objective type question, Please click question title for correct answer.
What is the difference between Count() and LongCount() extension methods in LINQ ?

    

public static long display()
{
var tempval = (from h in objDB.tbl_mvc_login
select h).Count ();

return tempval;
}



    

public static long display()
{
var tempval = (from h in objDB.tbl_mvc_login
select h).LongCount ();

return tempval;
}


Look carefully to the above methods declared. They both does the same thing but LongCount() has a greater range than Count(). According to MSDN, it has the range from

long.MinValue = -9223372036854775808

long.MaxValue = 9223372036854775807


which is quite big. Its DotNet Framework type is System.Int64. While count() DotNet Framework type is System.Int32 which has a range from

long.MinValue = -2,147,483,648

long.MaxValue = 2,147,483,647


So, next time if you want to count something which is quite big then use LongCount() extension method otherwise use Count().


Thanks and Regards
Akiii
Can you explain in brief about Aggregate() extension method in LINQ ?


public static int display()
{
int[] numbersArray = { 1, 2, 3, 4, 5 };

return numbersArray.Aggregate((x1, x2) => x1 * x2);
}


output : 120


In the above code, "numbersArray" is an integer array. Here, the first one being the first number or the previous result, and the second one is the second or next number to participate the calculation.

The calculation goes like :-

1 * 1 = 1 (stored in x1)
x1 * 2 = 2 (stored in x1)
x1 * 3 = 6 (stored in x1)
x1 * 4 = 24 (stored in x1)
x1 * 5 = 120 (stored and returned back)



Thanks and Regards
Akiii
What is the difference between FirstOrDefault() and SingleOrDefault() extension method in LINQ ?

FirstOrDefault() = gets the first item that matches a given criteria.

SingleOrDefault() = if you specify this extension method that means you are specifically saying that there can be only one value that matches the criteria. If there are more then 1 value that matches the criteria, throw an exception.



Thanks and Regards
Akiii
What is the difference between First() and Single() extension methods in LINQ ?

First() - There is at least one result, an exception is thrown if no result is returned.

Single() - There is exactly 1 result, no more, no less, an exception is thrown if no result is returned.


Thanks and Regards
Akiii
How to get the Value of attribute from XML using XDocument class?

Let us look at the below situation

<?xml version='1.0' encoding='UTF-8'?>

<Countries>
<State Name = 'Karnataka'>
<City Name='Bangalore' />
<City Name= 'Guledgudda' />
<City Name= 'Hubli' />
<City Name= 'Tumkur' />
</State>
</Countries>

The challenge is to get the City Names using XDocument class. The below code will help us to do so

string inputXml = @"<?xml version='1.0' encoding='UTF-8'?>

<Countries>
<State Name = 'Karnataka'>
<City Name='Bangalore' />
<City Name= 'Guledgudda' />
<City Name= 'Hubli' />
<City Name= 'Tumkur' />
</State>
</Countries>";
XDocument countrySource = XDocument.Parse(inputXml);

//The query

countrySource
.Descendants("State")
.SelectMany(i => i.Elements())
.ToList()
.ForEach(i=>Console.WriteLine((string)i.Attribute("Name")));


//Output
Bangalore
Guledgudda
Hubli
Tumkur

Explain with an example how to perform group by in LINQ/LAMBDA?

Consider the below input

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

The problem is to write a query using LINQ and LAMBDA that will count the nunber of fruits.

Solution
var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };


//Using LINQ
(from a in input
group a by a into g
select new
{
Key = g.Key
,Count = g.Count()

})
.ToList()
.ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));

//Using Lambda
input
.GroupBy(g => g)
.Select(i => new { Key = i.Key, Count = i.Count() })
.ToList()
.ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));


Output
Number of Apple is 3

Number of Banana is 1
Number of Mango is 2
Number of Orange is 1
Number of Strawberry is 1

How to assign a computed value to the same array back?

Consider the below input

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };


The problem is to write a query using LINQ that will count the number of fruits and will assign back the value to the same array i.e. we should not create another array for storing the computed values.

Solution


var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

input = (from a in input
group a by a into g
where g.Count() >= 2
select g.Key + " ( " + g.Count() + " )").ToArray();


Output
Apple ( 3 )

Mango ( 2 )

How will you obtain the length of the longest string in a Data table assuming that every column in of type string using Lambda?

DataTable dt = new DataTable();


var maxLength = dt.AsEnumerable()
.SelectMany(r => r.ItemArray.OfType<string>())
.Max(i => i.Length);


First cast the Datatable to System.Collections.Generic.IEnumerable<T> object by using the AsEnumerable() extension method,then using the SelectMany extension method
to find out the items in the ItemArray whose type is string and finally figuring out the max length of the records.
How will you obtain the length of the longest string in every column of a Datatable assuming that every column in of type string using Lambda?

DataTable dt = new DataTable();


var maximumColumnsLengths =
Enumerable.Range(0, dt.Columns.Count)
.Select(col => dt.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();

Write a code snippet for Left outer join using LINQ?

I failed to answer this question in my interview session. So I searched the answer for the question and found in MSDN. After my understanding I just wrote a simple program to understand the left outer join in LINQ.

namespace LeftOuterJoin
{ namespace LeftOuterJoin
{
class Employee
{
public string EmpName { get; set; }
public int EmpAge { get; set; }
public string EmpDeptID { get; set; }
}
class Department
{
public string DeptID { get; set; }
public string DeptName { get; set; }
}
class Program
{
public static void Main(string[] args)
{
Employee objEmp1 = new Employee { EmpName = "Naga", EmpAge = 29, EmpDeptID = "1" };
Employee objEmp2 = new Employee { EmpName = "Sundar", EmpAge = 30, EmpDeptID = "2" };
Employee objEmp3 = new Employee { EmpName = "Siva", EmpAge = 28, EmpDeptID = "3" };
Employee objEmp4 = new Employee { EmpName = "Shankar", EmpAge = 31, EmpDeptID = "4" };
Department objDept1 = new Department { DeptID = "1", DeptName = "IT" };
Department objDept2 = new Department { DeptID = "2", DeptName = "Admin" };
Department objDept3 = new Department { DeptID = "3", DeptName = "Testing" };
Department objDept4 = new Department { DeptID = "4", DeptName = "HR" };
Department objDept5 = new Department { DeptID = "5", DeptName = "Sales" };
//Creating List of Objects
List<Employee> employees = new List<Employee> { objEmp1, objEmp2, objEmp3, objEmp4 };
List<Department> depts = new List<Department> { objDept1, objDept2, objDept3, objDept4, objDept5 };
//Left Side Department Right side Employee
var DeptEmpCollection = from dept in depts
join emp in employees on dept.DeptID equals emp.EmpDeptID into de
from Employees in de.DefaultIfEmpty()
select new { dept.DeptName, EmployeesName = (Employees == null ? "--No Employee--" : Employees.EmpName) };
foreach (var EmpDept in DeptEmpCollection)
{
Console.WriteLine("Dept {0}, EmpName {1}", EmpDept.DeptName, EmpDept.EmployeesName);
}
Console.Read();
}
}
}
}

Write a query to get the single employee name when there are many employees whose name is "test" in the database ?

var employee = (from h in contextobject.Employee 

where h.EmployeeName == "test"
select h).FirstOrDefault<Employee>();




Thanks and Regards
Akiii
Write a query to get the list of all employees whose name is "test" ?

var employeeList = (from h in context.Employee

where h.EmployeeName == "test"
select h).ToList<Employee>();




Thanks and Regards
Akiii
IEnumerable Vrs IQueryable

IEnumerable Vrs IQueryable


In Linq, to query data from database and collections we use IEnumerable and IQueryable. IEnumerable is inherited by IQueryable, so it has all features of it and of its capabilities. Both has their own importance to query data and data manipulation.


IEnumerable :-

1. It exists in System.Collection namespace.
2. It can move forward only over collection.
3. It is best to query data from in-memory collections like Array, List, etc.
4. It is suitable for Linq to Objects and Linq To Xml queries.
5. It doesn't support lazy loading, hence not suitable for paging like scenario.

DataContextClasses db= new DataContextClasses();
IEnumerable<Employee>List =dc.Employees.Where(m=>m.Name.StartsWith("a"));
list=list.Take<Employee>(10);


IQueryable :-

1. It exists in System.Linq namespace.
2. It can move forward only over collection.
3. It is best to query data from out-memory like remote database.
4. It is suitable for Linq to Sql queries.
5. It support lazy loading, hence suitable for paging like scenario.

DataContextClasses db= new DataContextClasses();
IQueryable<Employee>List =dc.Employees.Where(m=>m.Name.StartsWith("a"));
list=list.Take<Employee>(10);
What is different between LINQ and Stored Procedure?

1.We can debug LINQ as it is part of .Net, whereas Stored procedure can’t be.

2. Deployment is easy with LINQ as everything compiled into DLL whereas with Stored procedure script is required for deployment.

3. At compile time we can find error, if any in LINQ but it not possible with Stored procedure.
Disadvantage of LINQ over Stored procedure?

Stored procedure compiles one time and executed every time whereas LINQ compiled everytime , so Stored Procedure is faster as compare to LINQ.
What is var?

Var is used to declare implicitly typed local variable means it tells compiler to figure out the type of the variable at compile time.
Since, 'var' is anonymous type, hence it is used where we don't know the type of output like joining of two tables.

var q = (from e in tblEmployee
join d in tblDepartment
on e.DeptID equals d.DeptID
select new
{
e.EmpID, e.FirstName, d.DeptName
});
What is Language Integrated Query (LINQ)?

NOTE: This is objective type question, Please click question title for correct answer.
Write the basic steps to execute a LINQ query

NOTE: This is objective type question, Please click question title for correct answer.
What is the function of the DISTINCT clause in a LINQ query

NOTE: This is objective type question, Please click question title for correct answer.
Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Interview Questions and Answers Categories