linq/reproductions.cs - Reproduction of some central query operations. | Lecture 16 - slide 7 : 11 Program 1 |
using System; using System.Collections.Generic; public static class LinqQueryOperations{ public static IEnumerable<TTarget> MySelect<TSource,TTarget> (this IEnumerable<TSource> source, Func<TSource,TTarget> selector){ foreach(TSource el in source) yield return selector(el); } public static IEnumerable<TSource> MyWhere<TSource> (this IEnumerable<TSource> source, Func<TSource,bool> predicate){ foreach(TSource el in source) if (predicate (el)) yield return el; } public static TSource MyAggregate<TSource> (this IEnumerable<TSource> source, Func<TSource,TSource,TSource> reducer){ IEnumerator<TSource> e = source.GetEnumerator(); bool sourceNotEmpty = e.MoveNext(); if (sourceNotEmpty){ TSource result = e.Current; while(e.MoveNext()) result = reducer(result, e.Current); return result; } else throw new InvalidOperationException("Source must be non-empty"); } public static int MyCount<TSource> (this IEnumerable<TSource> source){ return source .MySelect(p => 1) .MyAggregate((r,i) => r + i); } }