LINQ Flashcards
What is LINQ used for ?
LINQ can be used to perform operations on any data structure like arrays, SQL databases, collections, etc
How is query evaluated in LINQ?
In LINQ, query evaluations are lazy. That means the output of a LINQ query isn’t generated from the code that defines the query.
Instead, it’s generated when some code requests the results of the query.
What are aggregator methods
Aggregator methods return a single value calculated from all the elements in a sequence. the aggregator methods include Count, Sum, Min, Max, Average, and Aggregate.
Eg:
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double numSum = numbers.Sum();
Console.WriteLine($”The sum of the numbers is {numSum}”);
Complex example of Sum()
List<Product> products = GetProductList();</Product>
var categories = from p in products
group p by p.Category into g
select (Category: g.Key, TotalUnitsInStock: g.Sum(p => p.UnitsInStock));
foreach (var pair in categories)
{
Console.WriteLine($”Category: {pair.Category}, Units in stock: {pair.TotalUnitsInStock}”);
}
How LINQ is useful than Stored Procedures ?
Debugging: It is difficult to debug a stored procedure but as LINQ is part of.NET, visual studio debugger can be used to debug the queries
Deployment: For stored procedure, additional script should be provided but with LINQ everything gets compiled into single DLL hence deployment becomes easy
Type Safety: LINQ is type safe, so queries errors are type checked at compile time
Why SELECT clause comes before FROM in LINQ?
LINQ requires all variables
What are Anonymous Types ?
Anonymous types are types that are generated by compiler at run time. When we create a anonymous type we do not specify a name.
We just write properties names and their values. Compiler at runtime create these properties and assign values to them.
var k = new { FirstProperty = “value1”, SecondProperty = “value2” };
Console.WriteLine(k.FirstProperty)
What are some restrictions on Anonymous Types?
Anonymous types can not implement interfaces.
Anonymous types can not specify any methods.
We can not define static members.
All defined properties must be initialized.
We can only define public fields.
What is Anonymous Function ?
An Anonymous function is a special function that does not have any name.
We just define their parameters and define the code into the curly braces.
Give Example of Anonymous Function ?
delegate int func(int a, int b);
static void Main(string[] args)
{
func f1 = delegate(int a, int b)
{
return a + b;
};
Console.WriteLine(f1(1, 2)); }
What is Lazy and Deferred?
Lazy means “don’t do the work until you absolutely have to.”
Deferred means “don’t compute the result until the caller actually uses it.”
What is Let Clause?
In a query expression, it is sometimes useful to store the result of a sub-expression in order to use it in subsequent clauses.
You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you supply.
var names = new string[] { “Dog”, “Cat”, “Giraffe”, “Monkey”, “Tortoise” };
var result =
from animalName in names
let nameLength = animalName.Length
where nameLength > 3
orderby nameLength
select animalName;
What are LINQ Compiled Queries?
There may be scenario where we need to execute a particular query many times and repeatedly. LINQ allows us to make this task very easy by enabling us to create a query and make it compiled always. Benefits of Compiled Queries:
Query does need to compiled each time so execution of the query is fast.
Query is compiled once and can be used any number of times.
Query does need to be recompiled even if the parameter of the query is being changed.
Difference between IEnumerable and IQueryable?
The difference between IQueryable and IEnumerable is where the filter logic is executed. One executes on the client side(IEnumerable) and the other executes on the database(IQueryable).
Is LINQ - query syntax more performant than method syntax?
There is no semantic or performance difference between the two forms
How to enable linq querying for a remote data source?
By implementing iqueryable<T> interface</T>
What are iqueryable linq providers?
Linq providers that implement iqueryable interface that acts as a underlying bridge between linq query expressions and underlying datasource like database. EF datacontext implements iqueryable . This translates and executes queries against db
What is query variable in linq?
Any variable that stores query instaed of results of query . It’s execution occurs in foreach statement or movenext() method
What is Select?
Select transforms a collection by applying a mapping function to every element
What is Any?
Any checks if a collection is empty or has atleast one element matching a condition. It doesn’t return a new collection , but either true or false
What is All?
Unlike any, All checks if every element inside a collection matches a condition. It also returns either true or false instead of a new collection
What is GroupBy?
It groups the elements of a collection based on a key. It returns a collection of groups or buckets organized by a key
What is First and FirstOrDefault?
First and FirsyOrDefault return the first element in a collection or the firstone matching a condition. First throws an exception if the collection is empty or doesn’t match element. FirstOrDefault returns the default value of the element type instead
Single vs first
Single will throw an exceptiin if it finds more than one record matching the criteria. First will always select the first record from the list