C# 循环遍历字典对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14719955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:47:53  来源:igfitidea点击:

Looping through dictionary object

c#.net

提问by user1833222

I am very new to .NET, used to working in PHP. I need to iterate via foreachthrough a dictionary of objects. My setup is an MVC4 app.

我对 .NET 很陌生,习惯于在 PHP 中工作。我需要通过foreach对象字典进行迭代。我的设置是一个 MVC4 应用程序。

The Model looks like this:

该模型如下所示:

public class TestModels
{
    Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
    {
        {1, new {name="abc", age="1"}},
        {2, new {name="def", age="2"}}
    }
}

Controller:

控制器:

public class TestController : Controller
{
   Models.TestModels obj = new Models.TestModels();
}

How do I loop through the objobject and retrieve the values of the dictionary and print them in the view?

如何遍历obj对象并检索字典的值并在视图中打印它们?

回答by Sina Iravanian

One way is to loop through the keys of the dictionary, which I recommend:

一种方法是遍历字典的键,我推荐:

foreach(int key in sp.Keys)
    dynamic value = sp[key];

Another way, is to loop through the dictionary as a sequence of pairs:

另一种方法是将字典作为对的序列循环:

foreach(KeyValuePair<int, dynamic> pair in sp)
{
    int key = pair.Key;
    dynamic value = pair.Value;
}

I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keysproperty with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x)helps you retrieve the items in ascending order of the key. Note that Dictionaryuses a hash tabledata structure internally, therefore if you use the second method the order of items is not easily predictable.

我推荐第一种方法,因为如果您Keys使用适当的 LINQ 语句装饰属性,您可以更好地控制检索项目的顺序,例如,sp.Keys.OrderBy(x => x)帮助您按键的升序检索项目。请注意,内部Dictionary使用哈希表数据结构,因此如果您使用第二种方法,则项目的顺序不容易预测。

Update (01 Dec 2016): replaced vars with actual types to make the answer more clear.

更新(2016 年 12 月 1 日)var用实际类型替换s 以使答案更清晰。

回答by sa_ddam213

It depends on what you are after in the Dictionary

这取决于你在字典中追求什么

Models.TestModels obj = new Models.TestModels();

foreach (var keyValuPair in obj.sp)
{
    // KeyValuePair<int, dynamic>
}

foreach (var key in obj.sp.Keys)
{
     // Int 
}

foreach (var value in obj.sp.Values)
{
    // dynamic
}

回答by eandersson

You can do it like this.

你可以这样做。

Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
    Console.Write(item.Key);
    Console.Write(item.Value.name);
    Console.Write(item.Value.age);
}

The problem you most likely have right now is that the collection is private. If you add publicto the beginning of this line

您现在最有可能遇到的问题是该集合是私有的。如果您将public添加到此行的开头

Dictionary<int, dynamic> sp = new Dictionary<int, dynamic> 

You should be able to access it from the function inside your controller.

您应该能够从控制器内部的函数访问它。

Edit: Adding functional example of the full TestModelsimplementation.

编辑:添加完整TestModels实现的功能示例。

Your TestModelsclass should look something like this.

你的TestModels类应该看起来像这样。

public class TestModels
{
    public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();

    public TestModels()
    {
        sp.Add(0, new {name="Test One", age=5});
        sp.Add(1, new {name="Test Two", age=7});
    }
}

You probably want to read up on the dynamickeyword as well.

您可能还想阅读dynamic关键字。

回答by John smith

public class TestModels
{
    public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();

    public TestModels()
    {
        sp.Add(0, new {name="Test One", age=5});
        sp.Add(1, new {name="Test Two", age=7});
    }
}