I’m looking for the shortest code to create methods to perform common operations on items in an IEnumerable.
For example:
public interface IPupil { string Name { get; set; } int Age { get; set; } }
- Summing a property – e.g. IPupil.Age in IEnumerable<IPupil>
- Averaging a property – e.g. IPupil.Age in IEnumerable<IPupil>
- Building a CSV string – e.g. IPupil.Name in IEnumerable<IPupil>
I’m interested in the various approaches to solve these examples: foreach (long hand), delegates, LINQ, anonymous methods, etc…
Sorry for the poor wording, I’m having trouble describing exactly what I’m after!
Summing and averaging: easy with LINQ:
Building a CSV string – there are various options here, including writing your own extension methods. This will work though:
Note that it’s tricky to compute multiple things (e.g. average and sum) in one pass over the data with normal LINQ. If you’re interested in that, have a look at the Push LINQ project which Marc Gravell and I have written. It’s a pretty specialized requirement though.