LoginSignup
3
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-01-29

やりたいこと

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#?

3
1
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
3
1