LINQ Flashcards

1
Q

LINQ

A

for the application to be able to retrieve the data from sql server

the developer needs to know ado.net and Transact- sql

LINQ stands for Language Integrated Query. LINQ enables us to query any type of data store (SQL Server, XML documents. Objects in memory like list of customers or array etc). it could be entities or dataset

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why should we use LINQ

A

If the .NET application that is being developed

a) Requires data from SQL Server - Then the developer has to understand ADO.NET code and SQL specific to SQL Server Database
b) Requires data from an XML document - Then the developer has to understand XSLT & XPATH queries

c) Need to query objects in memory (List, List etc) - Then the developer has to understand how to work with objects in memory

LINQ enables us to work with these different data sources using a similar coding style without having the need to know the syntax specific to the data source. In our upcoming videos we will discuss querying different data sources using LINQ.

Another benefit of using LINQ is that it provides intellisense and compile time error checking.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

LINQ Architecture & LINQ Providers

A
  1. LINQ query can be written using any .NET supported programming language
  2. LINQ provider is a component between the LINQ query and the actual data source, which converts the LINQ query into a format that the underlying data source can understand. For example LINQ to SQL provider converts a LINQ query to T-SQL that SQL Server database can understand.

we also have LINQ to SQL, LINQ to objects, LINQ to Entities

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

using LINQ to SQL

A

Step 1: Create a new empty asp.net web application and name it Demo

Step 2: Click on “View” menu item and select “Server Explorer”

Step 3: In “Server Explorer” window, right click on “Data Connections” and select “Add Connection” option

Step 4: Specify your SQL Server name and the credentials to connect to SQL Server. At this point we should be connected to SQL Server from Visual Studio.

Step 5: Adding LINQ to SQL Classes

a) Right click on the “Demo” project in solution explorer and select “Add New Item” option
b) In the “Add New Item” dialog box, select “Data” under “Installed Templates”
c) Select “LINQ to SQL Classes”
d) Set Name = Sample.dbml
e) Finally click “Add” button

Step 6: From “Server Explorer” window drag and drop “Students” table onto “Sample.dbml” designer file.

Step 7: Add a webform. Drag and drop a gridview control.

Step 8: Copy and paste the following code in the code-behind file
using System;
using System.Linq;
namespace Demo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SampleDataContext dataContext = new SampleDataContext();
GridView1.DataSource = from student in dataContext.Students
where student.Gender == “Male”
select student;
GridView1.DataBind();
}
}
}

Notice that, with LINQ we are getting intellisense. If we misspell the table or column names we will get to know about them at compile time. Open SQL Profiler. Run the application, and notice the SQL Query that is generated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Query syntax

A

int[] numbers ={1,2,3,4,5,6,7,8,9};

Gridview1.Datasource = from number in numbers
where (number % 2) ==0
select number;

//from sql

Gridview1.Datasource = from student in datacontext.Students
where student.gender==”Male”
select student;

from varaibleName in dataset
where condition
select that record with VariableName;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

different ways of writing LINQ Queries

A

There are 2 ways to write LINQ queries using these Standard Query Operators
1. Using Lambda Expressions. We discussed Lambda Expressions in detail in Part 99 of C# Tutorial

  1. Using SQL like query expressions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

LINQ Standard Query Operators

A
To write LINQ queries we use the LINQ Standard Query Operators. The following are a few Examples of Standard Query Operators
select
from
where 
orderby 
join
groupby
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

query expressions are translated into their lambda expressions

A

From a performance perspective there is no difference between the two. Which one to use depends on your personal preference. But keep in mind, behind the scene, LINQ queries written using SQL like query expressions are translated into their lambda expressions before they are compiled.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

The Standard Query Operators are implemented as extension methods on IEnumerable

A

The Standard Query Operators are implemented as extension methods on IEnumerable interface. We will discuss, what extension methods are and how to implement them in a later video session.

on all the types that have implemented IEnumerable, we should be able to use these linq standard query operators

arrays implement Ienumerable
Non-generic collection classes that are present in systems.collection namespace like arraylist, hash table implement Ienumerable
Generic collection classes like list, dictionary, implement IEnumerable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

SQL like query expression

A

the query body must either end with select clause or a group clause

LINQ query using using SQL like query expressions
IEnumerable students = from student in Student.GetAllStudents()
where student.Gender == “Male”
select student;

To bind the results of this LINQ query to a GridView
GridView1.DataSource = students;
GridView1.DataBind();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

lambda expression

A

LINQ query using Lambda Expressions.
IEnumerable students = Student.GetAllStudents()
.Where(student => student.Gender == “Male”);

Where is an extension method on IEnumerable, as list implement Ienumearble, we could use on it

where return IEnumerable

To bind the results of this LINQ query to a GridView
GridView1.DataSource = students;
GridView1.DataBind();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

extension Methods in C#

A

string strName= “pragim”;
strName.ChangeFirstLetterCase();

options 1:
add this method to string class, but we do not own it, it belongs to .net framework

option 2:
why dont we create a base class, define the method there and inherit the string class. but that is not possible
as we do not own the string class

option 3:
Wrapper class/Helper

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Wrapper class/Helper

A
public class StringHelper
{
    public static string ChangeFirstLetterCase(string inputString)
    {
        if (inputString.Length > 0)
        {
            char[] charArray = inputString.ToCharArray();
            charArray[0] = char.IsUpper(charArray[0]) ?
                char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);
            return new string(charArray);
        }
    return inputString;
}

}

Wrapper class works, but the problem is, we cannot call ChangeFirstLetterCase() method using the following syntax.
string result = strName.ChangeFirstLetterCase();

Instead we have to call it as shown below.
string result = StringHelper.ChangeFirstLetterCase(strName);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

instead of wrapper, we want to call the method as an instance method defined in the string class

Convert ChangeFirstLetterCase() method to an extension method to be able to call it using the following syntax, as though it belongs to string class.
string result = strName.ChangeFirstLetterCase();
A

To convert ChangeFirstLetterCase() method to an extension method, make the following 2 changes

  1. Make StringHelper static class
  2. The type the method extends should be passed as a first parameter with this keyword preceeding it.

With these 2 changes, we should be able to call this extension method in the same way we call an instance method. Notice that the extension method shows up in the intellisense as well, but with a different visual clue.
string result = strName.ChangeFirstLetterCase();

Please note that, we should still be able to call this extension method using wrapper class style syntax. In fact, behind the scene this is how the method actually gets called. Extension methods are just a syntactic sugar.
string result = StringHelper.ChangeFirstLetterCase(strName);
So, this means we should also be able to call LINQ extension methods (select, where etc), using wrapper class style syntax. Since all LINQ extension methods are defined in Enumerable class, the syntax will be as shown below.
List Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

IEnumerable EvenNumbers = Enumerable.Where(Numbers, n => n % 2 == 0);

public static class StringHelper
{
    public static string ChangeFirstLetterCase(this string inputString)
    {
        if (inputString.Length > 0)
        {
            char[] charArray = inputString.ToCharArray();
            charArray[0] = char.IsUpper(charArray[0]) ?
                char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);
            return new string(charArray);
        }
    return inputString;
}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

extension method symbol

A

string res= strName.theextensionMethod name is shown as downward arrow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

wrapper class used for the extension methods

A
Please note that, we should still be able to call this extension method using wrapper class style syntax. In fact, behind the scene this is how the method actually gets called. Extension methods are just a syntactic sugar.
string result = StringHelper.ChangeFirstLetterCase(strName);

List Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

IEnumerable EvenNumbers = Enumerable.Where(Numbers, n => n % 2 == 0);

Enumerable class has the method defined for Where, it is present in system.Linq namespace

17
Q

What are Extension Methods

A

According to MSDN, Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

18
Q

LINQ Standard Query Operators types

A
LINQ Standard Query Operators also called as LINQ extension methods can be broadly classified into the following categories
Aggregate Operators
Grouping Operators
Restriction Operators
Projection Operators
Set Operators
Partitioning Operators
Conversion Operators
Element Operators
Ordering Operators
Generation Operators
Query Execution
Join Operators
Custom Sequence Operators
Quantifiers Operators
Miscellaneous Operators
19
Q

Aggregate operator - min

A

we use system.Linq
int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        int smallestNumber = Numbers.Min();

smallest even number:
int smallestEvenNumber = Numbers.Where(n => n % 2 == 0).Min();

where returns Ienumerable and applying Min operator on it

20
Q

nullable int

A

int? result =null;

result.HasValue

21
Q

Aggregate operator - max

A

int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  int largestNumber = Numbers.Max();
        int largestEvenNumber = Numbers.Where(n => n % 2 == 0).Max();
22
Q

Aggregate operator - sum

A

int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int sumOfAllNumbers = Numbers.Sum();
        int sumOfAllEvenNumbers = Numbers.Where(n => n % 2 == 0).Sum();
23
Q

Aggregate operator - count

A

int countOfAllNumbers = Numbers.Count();

int countOfAllEvenNumbers = Numbers.Where(n => n % 2 == 0).Count();

24
Q

Aggregate operator - Average

A

double averageOfAllNumbers = Numbers.Average();
double averageOfAllEvenNumbers = Numbers.Where(n => n % 2 == 0).Average();

average returns double

25
Q

Aggregate operator - min max with largest country name

A
using System;
using System.Linq;
namespace Demo
{
    class Program
    {
        static void Main()
        {
            string[] countries = { "India", "USA", "UK" };
        int minCount = countries.Min(x => x.Length);
        int maxCount = countries.Max(x => x.Length);

        Console.WriteLine
               ("The shortest country name has {0} characters in its name", minCount);
        Console.WriteLine
               ("The longest country name has {0} characters in its name", maxCount);
    }
} }
26
Q

Aggregate function

A

Example 1: Consider the following string array.
string[] countries = { “India”, “US”, “UK”, “Canada”, “Australia” };

We want to combine all these strings into a single comma separated string. The output of the program should be as shown below.
India, US, UK, Canada, Australia

Without LINQ, the program will be as shown below.
using System;
namespace Demo
{
    class Program
    {
        static void Main()
        {
            string[] countries = { "India", "US", "UK", "Canada", "Australia" };
        string result = string.Empty;
        for (int i = 0; i < countries.Length; i++)
        {
            result = result + countries[i] + ", ";
        }

        int lastIndex = result.LastIndexOf(",");
        result = result.Remove(lastIndex);

        Console.WriteLine(result);
    }
} }
With LINQ Aggregate function
using System;
using System.Linq;
namespace Demo
{
    class Program
    {
        static void Main()
        {
            string[] countries = { "India", "US", "UK", "Canada", "Australia" };
        string result = countries.Aggregate((a, b) => a + ", " + b);

        Console.WriteLine(result);
    }
} }

How Aggregate() function works?
Step 1. First “India” is concatenated with “US” to produce result “India, US”
Step 2. Result in Step 1 is then concatenated with “UK” to produce result “India, US, UK”
Step 3: Result in Step 2 is then concatenated with “Canada” to produce result “India, US, UK, Canada”

This goes on until the last element in the array to produce the final single string “India, US, UK, Canada, Australia”

27
Q

Aggregate function Compute the product of all numbers

A
Without LINQ
using System;
namespace Demo
{
    class Program
    {
        static void Main()
        {
            int[] Numbers = { 2, 3, 4, 5 };
            int result = 1;
            foreach (int i in Numbers)
            {
                result = result * i;
            }
        Console.WriteLine(result);
    }
} }
With LINQ:
using System;
using System.Linq;
namespace Demo
{
    class Program
    {
        static void Main()
        {
            int[] Numbers = { 2, 3, 4, 5 };
        int result = Numbers.Aggregate((a, b) => a * b);

        Console.WriteLine(result);
    }
} }

How Aggregate() function works?
Step 1: Multiply (2X3) to produce result 6
Step 2: Result (6) in Step 1 is then multiplied with 4 (6X4) to produce result 24
Step 3: Result (24) in Step 2 is then multiplied with 5 (24X5) to produce final result 120

28
Q

Aggregate function with seed

A

onsider the following integer array
int[] Numbers = { 2, 3, 4, 5 };

One of the overloaded version of Aggregate() function has a Seed parameter. If we pass 10 as the value for Seed parameter
int result = Numbers.Aggregate(10, (a, b) => a * b);

1200 will be the result

Step 1: Multiply (10X2) to produce result 20
Step 2: Result (20) in Step 1 is then multiplied with 3 (20X3) to produce result 60
Step 3: Result (60) in Step 2 is then multiplied with 4 (60X4) to produce result 240
Step 4: Result (240) in Step 3 is then multiplied with 5 (240X5) to produce final result 1200

29
Q

ienumearble vs Iquerable

A

var result = dbContext.Employees.Where(x => x.Gender == “Male”)
.OrderByDescending(x => x.Salary)
.Take(5);

Step 7: Notice that the following SQL Query is executed against the database.
exec sp_executesql N’SELECT TOP (5) [t0].[ID], [t0].[Name], [t0].[Gender], [t0].[Salary]
FROM [dbo].[Employees] AS [t0]
WHERE [t0].[Gender] = @p0
ORDER BY [t0].[Salary] DESC’,N’@p0 nvarchar(4000)’,@p0=N’Male’

var result = dbContext.Employees.AsEnumerable()
.Where(x => x.Gender == “Male”)
.OrderByDescending(x => x.Salary).Take(5);

Step 9: Run the console application and notice the query generated in SQL Profiler.
SELECT [t0].[ID], [t0].[Name], [t0].[Gender], [t0].[Salary]
FROM [dbo].[Employees] AS [t0]

AsEnumerable operator breaks the query into 2 parts

  1. The “inside part” that is the query before AsEnumerable operator is executed as Linq-to-SQL
  2. The “ouside part” that is the query after AsEnumerable operator is executed as Linq-to-Objects

So in this example the following SQL Query is executed against SQL Server, all the data is brought into the console application and then the WHERE, ORDERBY & TOP operators are applied on the client-side
SELECT [t0].[ID], [t0].[Name], [t0].[Gender], [t0].[Salary]
FROM [dbo].[Employees] AS [t0]

So in short, use AsEnumerable operator to move query processing to the client side.

30
Q

IQueryable uses expression trees which can be modified as long as we don’t execute them (calling ToList() or ToArray() method)

A

There is huge difference between using LINQ on collection which are implementing IEnumerable and IQueryable. Long story short. When we’re using IEnumerable interface, as you’ve written, we’re working on objects which are stored in memory. In other hand IQueryable uses expression trees which can be modified as long as we don’t execute them (calling ToList() or ToArray() method). More about expression trees.

Common mistake is work on IEnumerable interface. Let's take an example. We've a repository which contains method GetAll() which returns IEnumerable. When we'll work with those implementation like in example below, we'll first load whole collection into memory, then we'll filter results, after that we'll skip 10 elements and at the end we'll take only 5 results.
var elements = _repository.GetAll().Where(a => a.Salary < 100).Skip(10).Take(5);
But if our repository would implement method GetAll() which would return IQueryable expression won't be executed until we explicity call ToList() method. For instance, when we'll work with Entity Framework on a database our expression will be translated into proper SQL query and we'll return only 5 elements (or less if condition won't be full fit) to our program.

To sum up. Be aware during work with LINQ. Check if you’re working on IEnumerable or IQueryable interfaces. It matters. Cheers.

BTW difference between IEnumerable and IQueryable is one of my favorite interview questions :)

either you could

31
Q

The IEnumerable works with collection in local memory whereas IQueryable works with queryable data provider. If you are working with LINQ to SQL then best is to work IEnumerable since you don’t work with live data and to add or remove call functions from DataConext class. IQueryable does not return list of its own rather it constructs query. To return list from IQueryable you need to use AsQueryable.

A

https://medium.com/falafel-software/understanding-ienumerable-and-iqueryable-in-c-bc438118b00d#:~:text=If%20you%20use%20IQueryable%2
0with,query%20against%20external%20data%20sources.

Some of the important points about IQueryable are as follows:
It implements IEnumerable so the results can be iterated using foreach
It is best suited to query against external data sources.
It creates query using an Expression Tree
It is used to query a queryable data source
When you use IQueryable, the query gets created using an Expression Tree. Further the LINQ provider converts the Expression tree into the real SQL query. Always remember that IQueryable does only construct query and it loads data in deferred way.
When to use IQueryable
Try answering the following questions,
Working with the queryable datasource
Need to apply filter on data at the datasource
Need to apply paging , composition
Working with external data source
Needs to load data in deferred way
Need to use foreach to iterate collection
If answer to all of the above questions are YES, then consider using IQueryable