C#迭代通过NameValueCollection中 [英] C# Iterate through NameValueCollection
问题描述
我有一个NameValueCollection中,并希望通过值进行迭代。目前,我这样做,但是看起来应该有一个更合适的方法来做到这一点:
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?
推荐答案
您可以拉平使用LINQ的集合,但它仍然是一个的foreach
循环,但现在更多的是隐含的。
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:
在
测试 - > [瓦尔]
Test -> [Val],
的Test2 - > [VAL1,VAL1,VAL2]
Test2 -> [Val1, Val1, Val2],
Test3的 - > [VAL1]
Test3 -> [Val1],
TEST4 - > [VAL4]
Test4 -> [Val4]
在
测试 - >缬氨酸,
的Test2 - > VAL1,
Test2 -> Val1,
的Test2 - > VAL1,
Test2 -> Val1,
的Test2 - >值2,
Test2 -> Val2,
Test3的 - > VAL1
Test3 -> Val1,
TEST4 - > VAL4
Test4 -> Val4
这篇关于C#迭代通过NameValueCollection中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!