7. What is inside LINQ? public static class FetchExtension{ public static IEnumerable<T> MyWhere<T>( this IEnumerable<T> list, Func<T, bool> cond){ foreach(var i in list){ if (cond(i)) yield return i; } } }
8. Imperative vs. declarative var result = new List<int>(); foreach(var i in list){ if(i % 2 == 0){ result.Add(i); } } var result = from i in list where i % 2 == 0 select i;
Editor's Notes
Func<…> is “function as type”These code blocks are equals.First type parameters are input parameters. The last type parameter is the return valueIn type declaration we already know the function type…
Instead of List<T> use the base classIEnumerable<T>- It is the base class for the lists (and LINQ) It doesn’t contain any kind of .RemoveAt(…) methods, so no-one will mess with your list
Using System.LinqFilter the ones that are not interesting
When you debug you notice what happens! Don’t do if(list.Count() == 0) but if(!list.Any()) so you don’t evaluate the whole list
Declarative is better: Higher level of abstaction Define what computer does, not howSQL-like syntax is not the point, but the functionality!SQL-like syntax is just one way to express .Where(i=>i%2==0);