-1

I have the following method that I use to traverse collections like IQueryCollection, IHeadersDictionary and IFormCollection

public static string ToString(IEnumerable<KeyValuePair<string, StringValues>> dic)
{
    string res = "";
    foreach (var item in dic)
    {
        res += item.Key + "=" + item.Value + "&";
    }
    return res.TrimEnd('&');
}

I was wondering if it would be possible to do it in a more " functional" style, using something like Select and String.Join method

I'm using dot-net-core 2.0

opensas
  • 60,462
  • 79
  • 252
  • 386

3 Answers3

1

Yes you can write it using a select, it's actually quite simple:

public static string ToString(IEnumerable<KeyValuePair<string, StringValues>> dic)
{
    return string.Join("&", dic.Select(_ => $"{_.Key}={_.Value}"));
}

Will it perform better, hard to say without testing, your version uses string concatenations which are probably not a good idea for a large number of string (StringBuilder) would be better. But I expect string.Join to do a better job than your version.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • This is one of the first things I tried, because of examples I saw on the web, but got the following error: error CS1061: 'IEnumerable>' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'IEnumerable>' could be found (are you missing a using directive or an assembly reference?)... I guess I must be missing something... – opensas Sep 03 '17 at 09:28
  • 1
    Are you sure you have a `using System.Linq;` in your file ? – Titian Cernicova-Dragomir Sep 03 '17 at 09:29
1

You have a few options:

  • Using Aggregate

    dic.Aggregate((res, item) => res + item.Key + "=" + item.Value + "&")
       .TrimEnd('&')
    
  • Using Select and string.Join

    string.Join("&", dic.Select(item => item.Key + "=" + item.Value))
    
  • Using Zip and string.Join if you are using a Dictionary instance instead of a list of KeyValuePairs:

    string.Join("&", dict.Keys.Zip(dict.Values, (key, value) => key + "=" + value))
    
EvilTak
  • 7,091
  • 27
  • 36
0

You can use

var result = from keyvaluepair in dictionary
        from value in keyvaluepair .Value
        select keyvaluepair .Key + "=" + value;

or try aggregate,

string result = values.Aggregate("",
              (key, pair) =>
                key + "=" + pair.Key + ":"
                  + pair.Value.Aggregate("",
                      (str, val) => str + "=" + val)
              );

There is already a post related to same in How do I combine the keys and values of a Dictionary into one List using LINQ?

Vijayanath Viswanathan
  • 8,027
  • 3
  • 25
  • 43