Weitere ähnliche Inhalte
Ähnlich wie Coding with LINQ, Patterns & Practices (20)
Mehr von Tuomas Hietanen (14)
Kürzlich hochgeladen (20)
Coding with LINQ, Patterns & Practices
- 2. LINQ (Monads)
• Two types of functions
– Queries and Aggreagtes
AGGREGATE:
- returns result
(Wrapper) Wrapped type,
In this case
IEnumerable<T>
QUERY:
- returns another container of the same type
© Tuomas Hietanen
- 3. LINQ SELECT = LIST.MAP
(Query)
MAP function:
IEnumerable< > IEnumerable< >
© Tuomas Hietanen
- 6. Other Aggregates
(to make things easier)
Function Aggregate
function
LIST.SUM Add every
to
LIST.COUNT Add (+1)
to
LIST.MAX Select bigger of
or
...
© Tuomas Hietanen
- 9. Old Legacy Way New C#, LINQ F#
var result = new List<T>(); var result = from x in xs let result =
foreach(var x in xs){ select … List.map (fun x -> ...) xs
result.Add(...); //same as
... var result = xs.Select(x=>...);
}
foreach(var x in xs){ var result = from x in xs let result =
if(x=...){...} where … List.filter(fun x -> ...) xs
} //same as
var result = xs.Where(x=>...);
var result = new T(); //many ways, based on //many ways, based on
foreach(var x in xs){ var result = xs.Aggregate(…); let result =
result = ...; List.fold (fun f -> ...) xs
...
} //also supports unfold
foreach(var x in xs){ var result = from x in xs //SelectMany is not pure,
foreach(var y in ...){ from y in … so depends on situation.
.... select … E.g. List.collect, or seq {...}
} //same as let result =
} var result = List.collect (fun x -> ...) xs
xs.SelectMany(...);
© Tuomas Hietanen
- 10. Do use lists!
• Don’t return Null. Prefer throw
InvalidOperationException on error and
Enumerable.Empty<T>() on case of empty list
• Don’t modify collections, do use new ones
list.RemoveAt(0)
newlist = list.Where(interestingItems => ...)
• Use IEnumerable<T> not List<T> or IList<T>
– It is the baseclass and default for LINQ
– You can always say .toList() to evaluate the lazy
collection.
© Tuomas Hietanen
- 11. Safe class design, avoid side effects
• Don’t reuse variables
x=x+1
y=x+1
• Avoid global and class variables. Use method
parameters
– Better for function composition
• Don’t overcapuslate layers or class structures
– No coding for fun: Focus on the functionality
• Declarative programming.
– ”yield return” is ok in some cases, but not really
declarative.
• Also old design practices do still apply (=> FxCop).
© Tuomas Hietanen
- 12. F# list vs seq
• List is F# default
– Linked list
– Good for recursive methods
• Seq is IEnumerable<T>
– Lazy evaluation
– Good for .NET interop
© Tuomas Hietanen