Greg Brattle February 2016

can this value be output with inline code in c#?

Please consider the following inline code:

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

If the Headers structure above were a Dictionary(string, string), the code above would output the following:

[MyHeaderKey1, MyHeaderVal1],[MyHeaderKey2, MyHeaderVal2]

However, the Dictionary value is a string[] so the following gets output instead:

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

I need to be able to generate output like the first code example but against the Dictionary with the string[] value. It's ok if I only take the first item of the Dictionary - string[] value. Can this be done with inline C#?


DPac February 2016

Yes. Use Linq Select.

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

EDIT: Since OP mentioned that the value is string[], the default x.Value as described above may not produced desired output. I'm not sure how OP would format the value of the dictionary item and assuming FormatThisArray is a function that formats the array.

tede24 February 2016

If you just need the fist value:

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

Yacoub Massad February 2016

You need to do something like this:

var result =
        context.Request.Headers.Select(x =>
                "(" + string.Join(",", x.Value) + ")")));

This joins the individual items inside each string[] with a , and puts them between brackets.

Output would look like this:


Post Status

Asked in February 2016
Viewed 2,271 times
Voted 10
Answered 3 times


Leave an answer