C#通过NameValueCollection迭代 [英] C# Iterate through NameValueCollection

查看:489
本文介绍了C#通过NameValueCollection迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NameValueCollection ,并希望遍历这些值。目前,我这样做,但似乎应该有一个更简洁的方法来做:

  NameValueCollection nvc = new NameValueCollection(); 
nvc.Add(Test,Val1);
nvc.Add(Test2,Val1);
nvc.Add(Test2,Val1);
nvc.Add(Test2,Val2);
nvc.Add(Test3,Val1);
nvc.Add(Test4,Val4);

foreach(nvc中的字符串)
foreach(nvc.GetValues中的字符串v)
Console.WriteLine({0} {1},s, v)。

Console.ReadLine();

有吗?

解决方案

您可以使用Linq整理集合,但它仍然是 foreach 循环,但现在更隐式。

  var items = nvc.AllKeys.SelectMany(nvc.GetValues,(k,v)=> new {key = k,value = v}); 
foreach(项目中的var项)
Console.WriteLine({0} {1},item.key,item.value);

第一行将嵌套集合转换为匿名对象的(非嵌套)集合,属性



它现在是映射键 - >值而不是键 - >值集合 >。示例数据:



之前:


Test - > [Val]



Test2 - > [Val1,Val1,Val2],



Test3 - > [Val1] p>

Test4 - > [Val4]



$ b


测试 - > Val,



Test2 - > Val1,



Test2 - > Val1,



Test2 - > Val2,



Test3 - > Val1 ,



Test4 - > Val4



I have a NameValueCollection, and want to iterate through the values. Currently, I’m doing this, but it seems like there should be a neater way to do it:

NameValueCollection nvc = new NameValueCollection();
nvc.Add("Test", "Val1");
nvc.Add("Test2", "Val1");
nvc.Add("Test2", "Val1");
nvc.Add("Test2", "Val2");
nvc.Add("Test3", "Val1");
nvc.Add("Test4", "Val4");

foreach (string s in nvc)
    foreach (string v in nvc.GetValues(s))
        Console.WriteLine("{0} {1}", s, v);

Console.ReadLine();

Is there?

解决方案

You can flatten the collection with Linq, but it's still a foreach loop but now more implicit.

var items = nvc.AllKeys.SelectMany(nvc.GetValues, (k, v) => new {key = k, value = v});
foreach (var item in items)
    Console.WriteLine("{0} {1}", item.key, item.value);

The first line, converts the nested collection to a (non-nested) collection of anonymous objects with the properties key and value.

It's flatten in the way that it's now a mapping key -> value instead of key -> collection of values. The example data:

Before:

Test -> [Val],

Test2 -> [Val1, Val1, Val2],

Test3 -> [Val1],

Test4 -> [Val4]

After:

Test -> Val,

Test2 -> Val1,

Test2 -> Val1,

Test2 -> Val2,

Test3 -> Val1,

Test4 -> Val4

这篇关于C#通过NameValueCollection迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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