ディクショナリとLINQ

プログラミングC# 第6版 9.1.3


Dictionaryをクエリ式で処理します。

以下実装例

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

class Program {
    static void Main() {
        var hash = new Dictionary<string, int>();
        
        hash["a"] = 1;
        hash["b"] = 2;
        hash["c"] = 3;
        hash["d"] = 4;
        
        // 偶数のキーだけを削除する処理
        var ret = from h in hash.ToArray()
                  where h.Value % 2 == 0
                  select h.Key;
        foreach(var key in ret) {
            hash.Remove(key);
        }
        
        // 削除されかた確認
        foreach(var item in hash) {
            Console.WriteLine("key={0} val={1}",item.Key,item.Value);
        }
    }
}

ToArrayやToListを経由することでディクショナリのデータを取得し処理します。

次は逆に通常のデータからDictionaryへ変換するToDictionary演算子を使用してみます。

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

class Foo {
    public int id;
    public string name;
}

class Program {
    static void Main() {
        Foo[] fooList = new Foo[] {
            new Foo() { id = 2 , name = "foo1" },
            new Foo() { id = 2 , name = "foo2" },
            new Foo() { id = 2 , name = "foo3" },
            new Foo() { id = 3 , name = "foo4" },
            new Foo() { id = 3 , name = "foo5" },
        };
        
        // nameをキー、idを値に持つディクショナリを生成する
        var ret = fooList.ToDictionary(
            foo => foo.name,
            foo => foo.id
        );
        
        foreach(var item in ret) {
            Console.WriteLine("key={0} val={1}",item.Key,item.Value);
        }
    }
}
$ main
key=foo1 val=2
key=foo2 val=2
key=foo3 val=2
key=foo4 val=3
key=foo5 val=3

ただあれですね、この例だとgroup句でも同じような感じで実装できますね。

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

class Foo {
    public int id;
    public string name;
}

class Program {
    static void Main() {
        Foo[] fooList = new Foo[] {
            new Foo() { id = 2 , name = "foo1" },
            new Foo() { id = 2 , name = "foo2" },
            new Foo() { id = 2 , name = "foo3" },
            new Foo() { id = 3 , name = "foo4" },
            new Foo() { id = 3 , name = "foo5" },
        };
        
        var ret = from foo in fooList
                  group foo by foo.name;
        
        foreach(var item in ret) {
            foreach(var foo in item) {
                Console.WriteLine("name={0} id={1}",foo.name,foo.id);
            }
        }
    }
}
$ main
name=foo1 id=2
name=foo2 id=2
name=foo3 id=2
name=foo4 id=3
name=foo5 id=3

ToDictionaryとgroup句で使い分けが必要ですね。