8

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)
                             + ". ");
Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76
Alexander
  • 19,906
  • 19
  • 75
  • 162

5 Answers5

13

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);
Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76
1

LINQ comes with Select

Signature (Haskell style):

IEnumerable<TSource>.Select(Func<TSource->TResult>)->IEnumerable<TResult>
Adam Kewley
  • 1,224
  • 7
  • 16
1

You could use Dictionary, which is basically a collection of KeyValuePairs and do something like:

service.HttpResponseHeaders
                  .Select(kvp => kvp.Key + " -> " + String.Join(" - ", kvp.Value))
                  .Aggregate((s, sx) => s + ", " + sx);

Optimizing Aggregate: Optimizing Aggregate for String Concatenation

Community
  • 1
  • 1
Florian Gl
  • 5,984
  • 2
  • 17
  • 30
1

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);
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

You can use .Select() or if it is a List you can use .ConvertAll()

Here is the MSDN Documentation

Enumerable.Select

List.ConvertAll

David Pilkington
  • 13,528
  • 3
  • 41
  • 73