Skip to content

Instantly share code, notes, and snippets.

@wipiano
Last active October 8, 2017 07:11
Show Gist options
  • Save wipiano/8a4840c59fa78d85c7d60c15b8a7f3d5 to your computer and use it in GitHub Desktop.
Save wipiano/8a4840c59fa78d85c7d60c15b8a7f3d5 to your computer and use it in GitHub Desktop.
NameValueCollection で LINQ ref: http://qiita.com/wipiano/items/c70b84c5cc1b63db128b
public static NameValueCollection ParseQueryString(
string query
)
public static class NameValueCollectionExtensions
{
public static IEnumerable<KeyValuePair<string, IEnumerable<string>>> AsEnumerable(this NameValueCollection that)
{
return that.AllKeys
.Select(key => new KeyValuePair<string, IEnumerable<string>>(key, that.GetValues(key)));
}
public static IEnumerable<KeyValuePair<string, string>> AsFlattenEnumerable(this NameValueCollection that)
{
return that.AllKeys
.SelectMany(key => that.GetValues(key).Select(value => new KeyValuePair<string, string>(key, value)));
}
}
class Program
{
static void Main(string[] args)
{
var collection = new NameValueCollection()
{
{null, "nullValue1"},
{null, "nullValue2"},
{"", "emptyValue1"},
{"hoge", "hogehoge"},
{"fuga", "fugafuga"},
{"fuga", "fugafuga2"}
};
// IEnumerable<KeyValuePair<string, IEnumerable<string>>>
var enumerable = collection.AsEnumerable();
Console.WriteLine(Utf8Json.JsonSerializer.ToJsonString(enumerable));
// IEnumerable<KeyValuePair<string, string>>
var flatten = collection.AsFlattenEnumerable();
Console.WriteLine(Utf8Json.JsonSerializer.ToJsonString(flatten));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment