9. LINQ Operators || C# 10 Flashcards
What are the standart query operators categories?
Give an example of each
- Sequence in, sequence out (sequence -> sequence)
Where<>
,OrderBy<>
,ToList<>
and others.. - Sequence in, single element or scalar value out
First<>
,Count
,Contains<>
- Nothing in, sequence out (generation methods)
Empty
,Range
,Repeat
Explain:
Where<>
clause
Where
returns the elements from the input sequence that satisfy the given predicate:IEnumerable<string> query = names.Where(name => name.EndsWith("y"));
A Where<>
clause can appear more than once in a query and be interspersed with let
, orderby
and join
clauses.
What would be equivalent to SQL’s LIKE '%abc%'
? What other SQL command this method could substitute?
c.Name.Contains(“abc”). It can also act like IN
operator in SQL - checking if element is in the table.
Explain the difference between:
Take()
and Skip()
clauses
Take()
emits the first n
elements and discards the rest;Skip()
discards the first n
elements and emits the rest. So its opposite.
~~~
IQueryable<Book> query = dbContext.Books
.Where(b => b.Title.Contains("mercury"))
.OrderBy(b => b.Title).Skip(20).Take(20);
~~~</Book>
Explain the difference between:
-
Take(5..)
andSkip(5)
-
Take(..^5)
andSkipLast(5)
;
The meaning are equal in each row.
* Take(5..)
== Skip(5)
* Take(..^5)
== SkipLast(5)
Explain the difference between:
Distinct()
and DistinctBy<>
Distinct()
will return distinct elements in the given sequence;DistinctBy<>
will also return disctinct elements in a sequence but before apply the given logical operations. The returned results will be after the additional operation application such as:new[] {1.0, 1.1, 2.0, 2.1, 3.0, 3.1}.DistincBy(n => Math.Round(n, 0));
The first step will be to apply the logical operation, after which the sequence will look like this:new[] {1, 1, 2, 2, 3, 3}
. Then the Distinct()
method will take place and return only the distinct elements in the sequence. The result will be: 1, 2, 3
Define:
Select<>
clause
With Select
you always get the same number of elements that you started with. Each elements however, can be transformed in any manner by the mabda function:IEnumerable<string> query = FontFamily.Families.Select(s => s.Name);
It does also accept second parameter in lambda expression to enable indexed projection:IEnumerable<string> query = names.Select((s, i) => i + "=" + s);
// {“0=Tom”, “1=Harry”…}
Explain:
Correlated subquery
A subquery is correlated if it references an object in the outer query. In the example below it references ‘d’, the directory beingenumerated:
~~~
string tempPath = Path.GetPath();
DirectoryInfo[] dirs = new DirectoryInfo(tempPath).GetDirectories();
var query = from d in dirs
where (d.Attributes & FileAttributes.System) == 0
select new
{
DirectoryName = d.FullName,
Created = d.CreationTime,
Files = from f in d.GetFiles()
where (f.Attributes & FileAttributes.Hidden) == 0
select new {FileName = f.Name, f.Lenth, }
};
~~~
Explain the difference between:
Select
and SelectMany
Lets say we have a array of people names: string[] names = ["Harry Styles", "Lewis Capaldi", "Beyonce Knowles"];
and we would like to turn this into the array of names where first and last name is two separate items in array.
If we would use select we would take each element, use Split()
, which would return array of elements. We would make array of arrays and then make a double foreach loop to loop through and make something of that:
~~~
IEnumerable<string[]> splittedNames = names.Select(s => s.Split());
foreach(string[] stringArray in splittedNames){
foreach(string stringElement in stringArray){
…..
}
}
~~~
Now with SelectMany
we could do the same with a single line:
~~~
IEnumerable<string> query = names.SelectMany(s => s.Split());
foreach(string name in query){
.....
}
~~~
With `SelectMany` we can expand child sequences, flatten nested collections, and join two collections into a flat output sequence. If we would translate to query syntax `SelectMany` would have two range variables (from n in names...)</string>
What is the SelectMany
equivalent in SQL?
SelectMany
can perform cross-joins, non-equi joins, inner joins and left outer joins
How to include data from child table vs parent table in LINQ?
Child : each from
clause introduces a new child table.
Parent : to include data from a parent table you simply navigate to the property:
from c in dbContext.Customers select new { Name = c.Name, SalesPerson = c.SalesPerson.Name};
SalesPerson.Name is a parent property here
What is Select()
equivalent to in SQL?
Select()
subquery yields a result analogous to a left outer join: every outer element is included, regardless of whether it has any of other parameters
How we can turn left outer join to the inner join but written in LINQ?
We should replace Select()
(left outer join) with SelectMany()
: in the process of flattening the query we will switch to an inner join: customers are included only for whom one or more high-value purchases exist:
from c in dbContext.Customers from p in c.Purchaces where p.Price > 1000 select new { c.Name, p.Description, p.Price };
What is SQL equivalent of Join()
? How does this method work?
INNER JOIN
Applies a lookup strategy to match elements from two collections, emitting a flat result set
We can use both SelectMany()
and Join()
to inner join the elements with matching keys. Which is better over other?
Although both queries yield the same results, the Join()
query is considerably faster because its implementation in Enumerable preloads the inner collection (purchase) into a keyed lookup