获取NameValueCollection的所有值到字符串

Dem*_*tic 32 .net c# namevaluecollection

我有以下代码:

string Keys = string.Join(",",FormValues.AllKeys);
Run Code Online (Sandbox Code Playgroud)

我试图玩弄这个:

string Values = string.Join(",", FormValues.AllKeys.GetValue());
Run Code Online (Sandbox Code Playgroud)

但当然这不起作用.

我需要类似的东西来获取所有值,但我似乎没有找到相同的代码来执行相同的操作.

PS:我不想使用foreach循环,因为它胜过第一行代码的目的.

aba*_*hev 36

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"
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个扩展方法:

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

用法:

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

此外,您可以轻松转换NameValueCollection为更方便,Dictionary<string,string>所以:

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

得到:

var d = c.ToDictionary();
Run Code Online (Sandbox Code Playgroud)

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


Che*_*hen 26

string values = string.Join(",", collection.AllKeys.Select(key => collection[key]));
Run Code Online (Sandbox Code Playgroud)


Ant*_*ram 9

string values = 
    string.Join(",", FormValues.AllKeys.SelectMany(key => FormValues.GetValues(key)));
Run Code Online (Sandbox Code Playgroud)

编辑:其他答案可能是也可能不是你想要的.它们看起来更简单,但结果可能不是您在所有情况下所寻找的结果,但话说再次,它们可能是(您的里程可能会有所不同).

请注意,a NameValueCollection不像字典那样是1:1映射.您可以为同一个键添加多个值,这就是函数.GetValues(key)返回数组而不是单个字符串的原因.

如果您有一个已添加的集合

 collection.Add("Alpha", "1");
 collection.Add("Alpha", "2");
 collection.Add("Beta", "3");
Run Code Online (Sandbox Code Playgroud)

检索collection["Alpha"]产量"1,2".检索collection.GetValues("Alpha")产量{ "1", "2" }.现在,恰好您正在使用逗号将您的值一起合并为一个字符串,因此隐藏了这种差异.但是,如果您要加入其他值(例如感叹号),则其他答案的结果将是

"1,2!3"
Run Code Online (Sandbox Code Playgroud)

这里的代码就是

"1!2!3"
Run Code Online (Sandbox Code Playgroud)

使用演示您喜欢的行为的代码段.


HGM*_*aci 9

以下从URL参数列表创建一个字符串.

string.Join(", ", 
            Request.QueryString
                   .AllKeys
                   .Select(key => key + ": " + Request.QueryString[key])
      .ToArray())
Run Code Online (Sandbox Code Playgroud)

page.aspx?id=75&page=3&size=7&user=mamaci
Run Code Online (Sandbox Code Playgroud)

将会

id: 75, page: 3, size: 7, user: mamaci
Run Code Online (Sandbox Code Playgroud)