Can this value be output using inline code in C #?

Pay attention to the following built-in code:

string.Join(",", context.Request.Headers.ToArray())

If the header structure above was Dictionary(string, string), the code above would return the following:

[MyHeaderKey1, MyHeaderVal1],[MyHeaderKey2, MyHeaderVal2]

However, the value Dictionaryis equal string[], so instead, the output is:

[MyHeaderKey1, System.String[]],[MyHeaderKey2, System.String[]]

I need to be able to generate output as an example of the first code, but against Dictionaryc string[]. This is normal if I take only the first element of the value Dictionary- string[]. Can this be done using inline C #?

+4
source share
3 answers

Yes. Use Linq Select.

string.Join(",", context.Request.Headers.Select(x => string.Format("[{0}, {1}]", x.Key, FormatThisArray(x.Value))))

EDIT. OP , string[], x.Value, , . , OP , FormatThisArray - , .

+5

- :

var result =
    string.Join(",",
        context.Request.Headers.Select(x =>
            string.Format(
                "[{0},{1}]",
                x.Key,
                "(" + string.Join(",", x.Value) + ")")));

string[] , .

:

[MyHeaderKey1,(v1,v2,v3)],[MyHeaderKey2,(v4,v5,v6)]
+1

If you only need the first value:

string.Join(",", context.Request.Headers.Select(d=>new {d.Key,Value=d.Value.FirstOrDefault()}));
0
source

Source: https://habr.com/ru/post/1627867/


All Articles