Denys Wessels
Denys Wessels

Reputation: 17019

Lambda to count occurences of a string in IEnumerable

How can I re-write the GetCounts() method below in a one liner lambda expresssion? Please note, it has to be a lambda expression(cannot be LINQ). I'm trying to do something like this but can't figure out the exact syntax:

return items.GroupBy(e => e).ToDictionary<string, int>(e => e,e => e.Count());

Code:

static void Main(string[] args)
{
    string[] colours = new string[] { "Blue", "Blue", "Green", "Red" };
    Dictionary<string, int> values = GetCounts(colours);

    foreach (KeyValuePair<string, int> v in values)
        Console.WriteLine($"{v.Key}:{v.Value}");

    //Desired output:
    //Blue:2
    //Green:1
    //Red:1
    Console.ReadKey();
}

public static Dictionary<string, int> GetCounts(IEnumerable<string> items)
{
    var counts = new Dictionary<string, int>();

    foreach (string item in items)
        counts[item] = !counts.ContainsKey(item) ? 1 : ++counts[item];

    return counts;
}

Upvotes: 3

Views: 500

Answers (1)

JohanP
JohanP

Reputation: 5472

You need the grouping's Key

i.e.

items.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());

Upvotes: 5

Related Questions