CSharp - Use Average operator on non numeric elements

Introduction

First we retrieve the StudentOptionEntry objects.

Then we enumerate through the sequence of objects and display each.

At the end, we calculate the average and display it.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from  w w w  . ja va 2s.  com*/
{
    static void Main(string[] args)
    {
        IEnumerable<StudentOptionEntry> options =
          StudentOptionEntry.GetStudentOptionEntries();

        Console.WriteLine("Here are the Student ids and their options:");
        foreach (StudentOptionEntry eo in options)
            Console.WriteLine("Student id:  {0},  Options:  {1}", eo.id, eo.optionsCount);

        //  Now I'll get the average of the options.
        double optionAverage = options.Average(o => o.optionsCount);
        Console.WriteLine("The average of the Student options is: {0}", optionAverage);
    }
}
class StudentOptionEntry
{
    public int id;
    public long optionsCount;
    public DateTime dateAwarded;

    public static StudentOptionEntry[] GetStudentOptionEntries()
    {
        StudentOptionEntry[] empOptions = new StudentOptionEntry[] {
      new StudentOptionEntry {
        id = 1,
        optionsCount = 2,
        dateAwarded = DateTime.Parse("1990/12/31") },
      new StudentOptionEntry {
        id = 2,
        optionsCount = 10000,
        dateAwarded = DateTime.Parse("1992/06/30")  },
      new StudentOptionEntry {
        id = 2,
        optionsCount = 10000,
        dateAwarded = DateTime.Parse("1991/01/01")  },
      new StudentOptionEntry {
        id = 3,
        optionsCount = 5000,
        dateAwarded = DateTime.Parse("1997/09/30") },
      new StudentOptionEntry {
        id = 2,
        optionsCount = 10000,
        dateAwarded = DateTime.Parse("2000/04/01")  },
      new StudentOptionEntry {
        id = 3,
        optionsCount = 7500,
        dateAwarded = DateTime.Parse("1998/09/30") },
      new StudentOptionEntry {
        id = 3,
        optionsCount = 7500,
        dateAwarded = DateTime.Parse("1998/09/30") },
      new StudentOptionEntry {
        id = 4,
        optionsCount = 1500,
        dateAwarded = DateTime.Parse("1997/12/31") },
      new StudentOptionEntry {
        id = 101,
        optionsCount = 2,
        dateAwarded = DateTime.Parse("1998/12/31") }
    };

        return (empOptions);
    }
}

Result

Related Topic