Quantcast
Channel: dictionaryタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 99

C# Dictionaryのkeyとvalueを連結する

$
0
0

やりたいこと

Dictionaryの例
// サンプルデータ
var profile = new Dictionary<string, string>() {
    {"name", "お名前"},
    {"age", "30歳"},
    {"address", "日本"},
    {"blood", "AB型"},
};

という Dictionary を、以下のように keyとvalueを :で連結し、さらにそれらを 改行コード\n で連結する。
結果として、以下のような出力をしたい。

結果
name : お名前
age : 30歳
address : 日本
blood : AB型

やり方

以下のように、 String.Json と LinqのSelect で ワンライナーで実装する

実装
// サンプルデータ
var profile = new Dictionary<string, string>() {
    {"name", "お名前"},
    {"age", "20歳"},
    {"address", "日本"},
    {"blood", "AB型"},
};

var result = String.Join("\n", profile.Select(kvp => kvp.Key + " : " + kvp.Value));
Debug.Log(result);

おまけ:拡張メソッド

よく使われそうなので拡張メソッドにする

拡張メソッド実装
public static class DictionaryExtensions {

    public static string ToJoin<TKey, TValue>(
        this IDictionary<TKey, TValue> source, string separator, string join) 
    {
        return string.Join(separator, source.Select(kvp => kvp.Key.ToString()+join+kvp.Value.ToString()));
    }
}
使用例
// サンプルデータ
var profile = new Dictionary<string, string>() {
    {"name", "お名前"},
    {"age", "20歳"},
    {"address", "日本"},
    {"blood", "AB型"},
};

var result = profile.ToJoin("\n", " : ");
Debug.Log(result);

参考

How to use Aggregate method of Dictionary<> in C#?


Viewing all articles
Browse latest Browse all 99

Trending Articles