locked
Using Lambda Expressions To Count The Number Of Occurrences Of Values In A List RRS feed

  • Question

  • I have a list that looks something like this . . .

    List<string> l = new List<string>() { "A", "A", "A", "A", "B", "C", "C", "C", "C", "C", "D", "D" };

    . . . and I want to end up with a dictionary that counts the number of occurrences of each value in the list.  Something like this.

    Dictionary<string, int> d = new Dictionary<string, int>() { { "A", 4 }, { "B", 1 }, { "C", 5 }, { "D", 2 } };

    Would someone please provide an example of a way to do this using lambda expressions.  It seems like it should be pretty simple, but this one has me stumped.  Thanks!

    Thursday, July 19, 2012 5:21 PM

Answers

  • var dictionary = list.GroupBy(str => str)
        .ToDictionary(group => group.Key, group => group.Count());

    • Marked as answer by SMD- Thursday, July 19, 2012 5:30 PM
    Thursday, July 19, 2012 5:27 PM

All replies

  • var dictionary = list.GroupBy(str => str)
        .ToDictionary(group => group.Key, group => group.Count());

    • Marked as answer by SMD- Thursday, July 19, 2012 5:30 PM
    Thursday, July 19, 2012 5:27 PM
  • Thanks!  Proper use of "GroupBy" always confuses me.
    Thursday, July 19, 2012 5:29 PM