Datasheet
16
x
CHAPTER 1 PRIMER
{
return acc + 1;
}));
But even more intriguingly, a collection of Students can be “reduced” to an XML representation by
applying the same approach and transforming a
Student into a string representation:
string studentXML =
(Students.Reduce(“<students>”,
delegate(Student st, string acc)
{
return acc +
“<student>” +
st.FirstName +
“</student>”;
})) + “</students>”;
If some of this sounds familiar, it is because much of this was later expanded to be a major part
of the C# 3.0 release. LINQ, Language-Integrated Query, centers on these same core principles.
Using C# 3.0’s capability to defi ne new methods from “outside” a class (extension methods), C# 3.0
defi ned a series of these methods directly on the collection classes found in the .NET Framework
Class Library, thus making the
Database type even simpler:
class Database<T> where T : class
{
private List<T> data = new List<T>();
public Database() { }
public void Add(T i) { data.Add(i); }
public T Find(Predicate<T> algorithm)
{
return data.Find(algorithm);
}
public T[] FindAll(Predicate<T> algorithm)
{
return data.FindAll(algorithm).ToArray();
}
}
And, of course, if the List<T> holding the Student objects is available for public consumption, per-
haps via a property named
AsQueryable, as is the convention in LINQ, the Students’ ages can be
counted, summed, and averaged using a LINQ expression:
count =
Students.AsQuerayable.Aggregate(0, (acc, st) => ++acc);
sumAges =
Students.AsQuerayable.Aggregate(0,
(acc, st) => st.Age + acc);
averageAge =
Students.AsQuerayable.Aggregate(0.0F,
(acc, st) => ++acc)
/
Students.AsQuerayable.Aggregate(0.0F,
(acc, st) => st.Age + acc);
c01.indd 16c01.indd 16 10/1/2010 3:20:38 PM10/1/2010 3:20:38 PM