Datasheet

14
x
CHAPTER 1 PRIMER
public Database() { }
public void Add(T i) { data.Add(i); }
public IEnumerable<T> Filter(Predicate<T> pred)
{
List<T> results = new List<T>();
foreach (T it in data)
if (pred(it))
results.Add(it);
return results;
}
public IEnumerable<U> Map<U>(Func<T, U> transform)
{
List<U> results = new List<U>();
foreach (T it in data)
results.Add(transform(it));
return results;
}
public U Reduce<U>(U startValue, Accumulator<T, U> accum)
{
U result = startValue;
foreach (T it in data)
result = accum(it, result);
return result;
}
public T Find(Predicate<T> algorithm)
{
return Filter(algorithm).GetEnumerator().Current;
}
public T[] FindAll(Predicate<T> algorithm)
{
return new List<T>(Filter(algorithm)).ToArray();
}
}
When those three operations are in place, any other operation can be de ned in terms of those three
through various combinations of them.
By defi ning their parameters in terms of
IEnumerable<T>, instead of as a raw array as the earlier
defi nitions did, any sort of
IEnumerable<T> could be used, including lists, arrays, or even the anon-
ymous iterator defi ned using the C# 2.0 yield return statement:
public IEnumerable<T> Filter2(Predicate<T> pred)
{
foreach (T it in data)
if (pred(it))
yield return it;
}
public IEnumerable<U> Map2<U>(Func<T, U> transform)
c01.indd 14c01.indd 14 10/1/2010 3:20:38 PM10/1/2010 3:20:38 PM