Search code examples
c#.netlinqdelegatesanonymous-methods

Implementation options of summing, averaging, concatenating, etc items in an IEnumerable


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; }
}
  1. Summing a property - e.g. IPupil.Age in IEnumerable<IPupil>
  2. Averaging a property - e.g. IPupil.Age in IEnumerable<IPupil>
  3. 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!


Solution

  • 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.