My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.
C# CODE EXAMPLE created on Friday, July 02, 2010 permalink
How to use a generic dictionary to total enum values
This code example shows how you can use a generic dictionary to add up the total of each kind of item in an enum collection. It is flexible so that if you add an enum value, it automatically is totaled as well. See Dave Fancher's article showing how this approach is actually faster than various approaches with LINQ.
using System;
using System.Collections.Generic;

namespace TestDict2394343
{
    class Program
    {
        static void Main(string[] args)
        {

            List<LessonStatus> lessonStatuses = new List<LessonStatus>();
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Recorded);
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Prepared);
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Prepared);
            lessonStatuses.Add(LessonStatus.Defined);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Practiced);
            lessonStatuses.Add(LessonStatus.Prepared);
            lessonStatuses.Add(LessonStatus.Defined);

            Section section = new Section(lessonStatuses);
            section.ShowTotals();
            Console.ReadLine();

        }


        public class Section
        {
            protected Dictionary<string, int> _lessonStatusTotals = new Dictionary<string, int>();

            public Section(List<LessonStatus> lessonStatuses)
            {
                foreach (var lessonStatus in Enum.GetNames(typeof(LessonStatus)))
                {
                    _lessonStatusTotals.Add(lessonStatus, 0);
                }


                foreach (var lessonStatus in lessonStatuses)
                {
                    _lessonStatusTotals[lessonStatus.ToString()]++;
                }
            }

            public void ShowTotals()
            {
                foreach (KeyValuePair<string, int> lst in _lessonStatusTotals)
                {
                    Console.WriteLine("{0}: {1}", lst.Key, lst.Value);
                }
            }
        }

        public enum LessonStatus
        {
            Defined,
            Prepared,
            Practiced,
            Recorded
        }
    }
}
need markup?