Frequencies メソッドを作る

シーケンスに含まれる要素の出現回数を求める Frequencies メソッドを作ってみました。

using System;
using System.Collections.Generic;
using System.Linq;

static class Ext {
    public static Dictionary<T, int> Frequencies<T>(this IEnumerable<T> xs) {
        var d = new Dictionary<T, int>();
        foreach (var x in xs) {
            if (!d.ContainsKey(x))
                d[x] = 1;
            else
                d[x]++;
        }
        return d;
    }
}

class Program {
    static void Test<T>(T[] xs) {
        var d = xs.Frequencies().Select(e => $"{e.Key} {e.Value}");
        Console.WriteLine(string.Join(", ", d));
    }

    static void Main() {
        Test(new[] { 1, 2, 3, 1, 1, 2, 2 });
        // => 1 3, 2 3, 3 1

        Test(new[] { "foo", "bar", "foo", "buz" });
        // => foo 2, bar 1, buz 1

        Test(new[] { Tuple.Create(1, 2), Tuple.Create(1, 2), Tuple.Create(2, 3) });
        // => (1, 2) 2, (2, 3) 1
    }
}

実行結果です。

1 3, 2 3, 3 1
foo 2, bar 1, buz 1
(1, 2) 2, (2, 3) 1