IT TIP

어쨌든 사전을 String으로 편리하게 변환하는 것이 있습니까?

itqueen 2020. 11. 25. 21:49
반응형

어쨌든 사전을 String으로 편리하게 변환하는 것이 있습니까?


사전에서 ToString의 기본 구현이 내가 원하는 것이 아니라는 것을 알았습니다. 나는 갖고 싶습니다 {key=value, ***}.

그것을 얻는 편리한 방법이 있습니까?


이 확장 방법을 시도하십시오.

public static string ToDebugString<TKey, TValue> (this IDictionary<TKey, TValue> dictionary)
{
    return "{" + string.Join(",", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray()) + "}";
}

디버깅 목적으로 직렬화하려는 경우 더 짧은 방법은 다음을 사용하는 것입니다 String.Join.

var asString = string.Join(";", dictionary);

이 때문에 작동 IDictionary<TKey, TValue>구현 IEnumerable<KeyValuePair<TKey, TValue>>.


다음과 같은 확장 방법은 어떻습니까?

public static string MyToString<TKey,TValue>
      (this IDictionary<TKey,TValue> dictionary)
{
    if (dictionary == null)
        throw new ArgumentNullException("dictionary");

    var items = from kvp in dictionary
                select kvp.Key + "=" + kvp.Value;

    return "{" + string.Join(",", items) + "}";
}

예:

var dict = new Dictionary<int, string>
{
    {4, "a"},
    {5, "b"}
};

Console.WriteLine(dict.MyToString());

산출:

{4=a,5=b}

편리한 방법이 없습니다. 직접 굴려야합니다.

public static string ToPrettyString<TKey, TValue>(this IDictionary<TKey, TValue> dict)
{
    var str = new StringBuilder();
    str.Append("{");
    foreach (var pair in dict)
    {
        str.Append(String.Format(" {0}={1} ", pair.Key, pair.Value));
    }
    str.Append("}");
    return str.ToString();
}

아마도:

string.Join
(
    ",",
    someDictionary.Select(pair => string.Format("{0}={1}", pair.Key.ToString(), pair.Value.ToString())).ToArray()
);

먼저 각 키-값 쌍을 반복하고 문자열로보고 싶은 형식을 지정한 다음 나중에 배열로 변환하여 단일 문자열로 결합합니다.


나는이 간단한 대답을 얻었다 .. JavaScriptSerializer이것을 위해 Class를 사용하라 .

그리고 Dictionary 객체를 인자로하여 Serialize 메서드를 간단히 호출 할 수 있습니다.

예:

var dct = new Dictionary<string,string>();
var js = new JavaScriptSerializer();
dct.Add("sam","shekhar");
dct.Add("sam1","shekhar");
dct.Add("sam3","shekhar");
dct.Add("sam4","shekhar");
Console.WriteLine(js.Serialize(dct));

산출:

{"sam":"shekhar","sam1":"shekhar","sam3":"shekhar","sam4":"shekhar"}

Linq를 사용하려면 다음과 같이 시도해 볼 수 있습니다.

String.Format("{{{0}}}", String.Join(",", test.OrderBy(_kv => _kv.Key).Zip(test, (kv, sec) => String.Join("=", kv.Key, kv.Value))));

where "test" is your dictionary. Note that the first parameter to Zip() is just a placeholder since a null cannot be passed).

If the format is not important, try

String.Join(",", test.OrderBy(kv => kv.Key));

Which will give you something like

[key,value], [key,value],...

Another solution:

var dic = new Dictionary<string, double>()
{
    {"A", 100.0 },
    {"B", 200.0 },
    {"C", 50.0 }
};

string text = dic.Select(kvp => kvp.ToString()).Aggregate((a, b) => a + ", " + b);

Value of text: [A, 100], [B, 200], [C, 50]


You can loop through the Keys of the Dictionary and print them together with the value...

public string DictToString(Dictionary<string, string> dict)
{
    string toString = "";
    foreach (string key in dict.Keys)
    {
            toString += key + "=" + dict[key];
    }
    return toString;
}

I like ShekHar_Pro's approach to use the serializer. Only recommendation is to use json.net to serialize rather than the builtin JavaScriptSerializer since it's slower.


I really like solutions with extension method above, but they are missing one little thing for future purpose - input parametres for separators, so:

    public static string ToPairString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string pairSeparator, string keyValueSeparator = "=")
    {
        return string.Join(pairSeparator, dictionary.Select(pair => pair.Key + keyValueSeparator + pair.Value));
    }

Example of using:

string result = myDictionary.ToPairString(Environment.NewLine, " with value: ");

What you have to do, is to create a class extending Dictionary and overwrite the ToString() method.

See you

참고URL : https://stackoverflow.com/questions/5899171/is-there-anyway-to-handy-convert-a-dictionary-to-string

반응형