Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual C# Collection "map" function?

In Haskell we have the function

map (a -> b) -> [a] -> [b]

to change the type of a Collection using a function.

Is there something similar in C#?

Or what else is the fastest way to put a complete collection of KeyValuePairs into a debug message, for example?

I thought of sth like

debugmsg("http response is " + service.HttpResponseHeaders
                                      .Map<string>((k, v) => k + "->" + v)
                                      .Aggregate((s, sx) => s + "," + sx)
                             + ". ");
like image 844
Alexander Avatar asked Nov 06 '13 07:11

Alexander


People also ask

What is Visual C used for?

Microsoft Visual C++ is a integrated development environment (IDE) used to create Windows applications in the C, C++, and C++/CLI programming languages.

Is Microsoft Visual C free?

A fully-featured, extensible, free IDE for creating modern applications for Android, iOS, Windows, as well as web applications and cloud services.

Is Visual C necessary?

We don't recommend that you delete any Visual C++ redistributable, because doing so could make multiple applications on your computer stop working. Given how little space they take up and how broadly they are used, it doesn't seem worth the hassle to mess with your current ecosystem of standard library files.

Is Visual Studio C or C++?

C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cross-platform C and C++ development on Windows, Linux, and macOS.


2 Answers

In LINQ, map is named Select. Also, please note that any collection of KeyValuePair<TKey, TValue> will have only one argument in Select; you'll have to pull the Key and Value out of it.

service.HttpResponseHeaders.Select(kvp => kvp.Key + "->" + kvp.Value)
                           .Aggregate((s, sx) => s + "," + sx);
like image 83
Patryk Ćwiek Avatar answered Sep 20 '22 18:09

Patryk Ćwiek


As others have noted, you can map one type to another using Select. Creating the final string is best done using String.Join though, to avoid creating useless temporary strings.

Strings in .NET are immutable so adding two strings creates a new string. String.Join on the other hand uses a StringBuilder internally to add data to a mutable buffer and return the final result.

You should note though that HttpResponseHeaders contains multiple values for each key. Just converting the value to a string will not work.

The following will create a comma-separated list of values from the response headers. If the header has multiple values, they are separated by '|':

var headerStrings=from header in service.HttpResponseHeaders
            let headerValue=String.Join("|",header.Value)
            select String.Format("{0} -> {1}",header.Key,headerValue);
var message=String.Join(",",headerStrings);
like image 45
Panagiotis Kanavos Avatar answered Sep 20 '22 18:09

Panagiotis Kanavos