4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ネタ] C# でDictionary生成リテラル

Last updated at Posted at 2012-12-18

ごめんなさいネタです。

C#でも各種LLやF#にあるみたいな辞書リテラルがほしい!
ってことで、リテラルじゃないけどこんなのはどうか。


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

class Make
{
    public static Dictionary<string, T> Dict<T>(params Expression<Func<string, T>> []items)
    {
        return items.ToDictionary(
                    e => e.Parameters[0].Name, 
                    e => e.Compile()(null));
    }
}

メリット

  • 超自然に書ける。 var dict = Make.Dict(a => 1, b => 2);

デメリット

  • キーは文字列固定。かつ変数名として有効な文字列しか使えない
  • (多分)とても遅い

まあたかが辞書の生成でこんなことしてたら見あわないですよね。
もしかすると Pythonの**kwargs 的な用途で使えるシチュエーションはあるかもだけど。

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?