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; }
}
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:
var sum = pupils.Sum(pupil => pupil.Age);
var average = pupils.Average(pupil => pupil.Age);
Building a CSV string - there are various options here, including writing your own extension methods. This will work though:
var csv = string.Join(",", pupils.Select(pupil => pupil.Name).ToArray());
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.