获取一个NameValueCollection的所有值到一个字符串 [英] Get all values of a NameValueCollection to a string

查看:31
本文介绍了获取一个NameValueCollection的所有值到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

string Keys = string.Join(",",FormValues.AllKeys);

我正在尝试使用get:

I was trying to play around with the get:

string Values = string.Join(",", FormValues.AllKeys.GetValue());

但是那当然不行.

我需要类似的东西来获取所有值,但是我似乎没有找到合适的代码来做同样的事情.

I need something similar to get all the values, but I don't seem to find the appropriate code to do the same.

P.S:我不想使用 foreach 循环,因为这超出了第一行代码的目的.

P.S: I do not want to use a foreach loop since that beats the purpose of the first line of code.

推荐答案

var col = new NameValueCollection() { { "a", "b" }, { "1", "2" } }; // collection initializer

var values = col.Cast<string>().Select(e => col[e]); // b, 2

var str = String.Join(",", values );  // "b,2"

还可以创建扩展方法:

public static string Join(this NameValueCollection collection, Func<string,string> selector, string separator)
{
    return String.Join(separator, collection.Cast<string>().Select(e => selector(e)));
}

用法:

var s = c.Join(e => String.Format("\"{0}\"", c[e]), ",");


您还可以轻松地将 NameValueCollection 转换为更方便的 Dictionary< string,string> ,因此:


Also you can easily convert NameValueCollection to more handy Dictionary<string,string> so:

public static IDictionary<string,string> ToDictionary(this NameValueCollection col)
{
    return col.AllKeys.ToDictionary(x => x, x => col[x]);
}

赠予:

var d = c.ToDictionary();


正如我使用Reflector所发现的那样, NameValueCollection.AllKeys 在内部执行循环以收集所有te键,因此 c.Cast< string>()似乎更多更好.


As I found using Reflector, NameValueCollection.AllKeys internally performs a loop to gather all te keys, so it seems that c.Cast<string>() is more preferable.

这篇关于获取一个NameValueCollection的所有值到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆