04 Linq
04 Linq
SoftUni Team
Technical Trainers
Software University logo
Software University
https://softuni.bg
Have a Question?
sli.do
#csharp-db
2
Table of Contents
1. LINQ
▪ Filtering
▪ Select / Projection
▪ Aggregation
▪ Joining
▪ SelectMany
2. IEnumerable vs IQueryable
3. Result Models
3
Filtering and Aggregating Tables
Select, Join and Group Data Using LINQ
Filtering
▪ Where
▪ Selects values that are based on a predicate function
▪ Syntax
string[] words = { "the", "quick", "brown", "fox", "jumps" };
IEnumerable<string> query =
words.Where(word => word.Length == 3);
6
Good Reasons Not to Use Select
▪ Data that is selected is not of the initial entity type
▪ Anonymous type, generated at runtime
9
Grouping Tables in EF
▪ Grouping also can be done by LINQ
▪ The same way as with collections in LINQ
▪ Grouping with LINQ
var groupedEmployees =
from employee in softUniEntities.Employees
group employee by employee.JobTitle;
10
SelectMany – Example
11
SelectMany – Example
IEnumerable<Person> people = new List<Person>();
14
IQueryable<T>
▪ IQueryable<T> is an interface and it is available in
System.Linq
▪ Provides functionality to evaluate queries against a specific
data source where the type of the data may not be specified
▪ The IQueryable interface is intended for implementation by
query providers
▪ LINQ methods over IQueryable<T> use
Expression<Func<>> parameters (expression trees)
▪ Entity Framework can convert expression trees directly into SQL 15
Differences Between IEnumerable and IQueryable
▪ IEnumerable<T> ▪ IQueryable<T>
▪ System.Collections. ▪ System.Linq namespace
Generic ▪ Derives the base interface from
▪ Base type for almost all IEnumerable<T>
.NET collections ▪ LINQ methods works with
▪ LINQ methods works with Expression<Func<>>
Func<> ▪ Good for queries over data
▪ Good for in-memory data stores such as databases
16
Result Models
Simplifying Models
Result Models
▪ Select(), GroupBy() can work with custom classes
▪ Allow you to pass them to methods and use them
as a return type
▪ Require some extra code (class definition)
▪ Sample Result Model
public class UserResultModel
{
public string FullName { get; set; }
public string Age { get; set; }
}
18
Result Models
▪ Assign the fields as you would with an anonymous object
var currentUser = context.Users
.Where(u => u.Id == 8)
.Select(u => new UserResultModel
{
FullName = u.FirstName + " " + u.LastName,
Age = u.Age
})
.SingleOrDefault();
▪ ▪ LINQ
…
▪ ▪…Filtering, Aggregation, SelectMany, Joins
▪ ▪ IEnumerable
…
▪ IQueryable
▪ Differences between IEnumerable
and IQueryable
▪ Result Models
20
Questions?
SoftUni Diamond Partners
A picture containing logo
Shape
Text
Text
22
License
23
Trainings @ Software University (SoftUni)
▪ Software University – High-Quality Education, Software University logo
▪ facebook.com/SoftwareUniversity
24