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 (string s in nvc)
foreach (string v in nvc.GetValues(s))
Console.WriteLine("{0} {1}", s, v);
Console.ReadLine();
有吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用 Linq 展平集合,但它仍然是一个
foreach
循环,但现在更加隐式。第一行将嵌套集合转换为具有属性 key 和 value 的匿名对象的(非嵌套)集合。
它被扁平化了,现在它是一个映射键 ->值而不是键 ->值的集合。示例数据:
之前:
之后:
You can flatten the collection with Linq, but it's still a
foreach
loop but now more implicit.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:
After:
您可以使用键进行查找,而不是使用两个循环:
You can use the key for lookup instead of having two loops:
这里没有什么新东西可看(@Julian's +1'd by me 的答案在功能上是等效的),请大家继续前进。
我有一组[对于这种情况来说太过分但可能相关]扩展方法在相关问题的答案中,这将让你做:
Nothing new to see here (@Julian's +1'd by me answer is functionally equivalent), y'all move along y'all please.
I have an [overkill for this case but possibly relevant] set of extension methods in an answer to a related question, which would let you do:
或者当键可为空时:
OR when keys nullable:
我认为这更简单:VB.NET
C#:
I think this is simpler: VB.NET
C#:
我发现避免嵌套循环的唯一方法是使用附加列表来存储值:(
需要[仅] .NET 2.0 或更高版本)
The only way I found to avoid the nested loops is using additional List to store the values:
(Requires [only] .NET 2.0 or later)
这将返回所有键和相应的值。
This will return you all keys and corresponding values.