Upload
victor-matyushevskyy
View
1.367
Download
0
Tags:
Embed Size (px)
Citation preview
LINQ
Iterators
Iteration
Iteration
What do we see
• It is imperative (repetitive, verbose etc.)– Sort of awkward
• This is “default” way to iterate data structure– Can be put into library
• But sometimes we want to iterate differently– Determined by business rules
Custom iteration
Custom iteration
Custom iteration
The problem
Given:• Data structure knows how to iterate
itself• Additionally, we want to define other
ways to iterate data structure
Goal:• Nice abstraction for that
Solution
foreach loop
Agenda
• Manual iteration• …magic…• foreach iteration• …magic…• No iteration
Iterator pattern
Usage
Implementation
Let’s implement ReverseEnumerator<T>
ReverseEnumerator<T>
ReverseEnumerator<T>
Usage
Let’s make usage code identical
Now compiler can do iteration
for us
Iterators are lazy (deferred)
Let’s show it in debugger
Iteration side effects are observed
each time the sequence is iterated
Let’s see what else can compiler do for us
yield return – makes MoveNext() return true
yield return is also lazy
Let’s check that in debugger
yield return is lazy
yield return is lazy
yield break – makes MoveNext() return false
IEnumerables are immutable
We cannot change the sequenceWe can only create new sequences
based on old ones
We can chain iterators
Remember, the sequence is lazy
Infinite iterators
Infinite iterators
Let’s recall our goal
Given:• Data structure knows how to iterate
itself• Additionally, we want to define other
ways to iterate data structure
Goal:• Nice abstraction for that
Iterate data structure
In fact, often we don’t need iteration at all
Typical tasks:• Find element(s) in sequence• Check if condition is true/false for all
elements• Transform sequence • Filter sequence• Aggregate sequence
In these cases iteration is just an implementation detail
We can express what we want declaratively
Generation
• Empty(), Range(), Repeat()
Aggregation
• Aggregate(), All(), Any(), Average(), Contains(), Count(), Max(), Min(), Sum()
• ElementAt(), First(), Last(), Single()
Transformation
• Cast(), OfType()• Concat(), Distinct(), Except(),
Intersect(), Reverse(), Union(), Zip()• Select(), SelectMany()• GroupBy()• OrderBy(), OrderByDescending()
Filtration
• Skip(), SkipWhile(), TakeWhile(), Where()
Anonymous types
Extension methods are nice
But we’ve got something even better!
LINQ(Language Integrated Queries)(a.k.a. query comprehensions)
select
where
select + where
select + where + anonymous types
select many
select many + where
order by
let
group by
group by
Sum up
• Use LINQ and LINQ extension methods – to declaratively specify what you want – to simplify your code– to generalize your code– to create complex abstractions from
simple ones
• Remember that IEnumerables are lazy
Questions?