c# - 在 C# 中循环字典

标签 c# .net dictionary

我有以下使用类和字典的代码,该类和字典需要状态和资本,但我无法通过循环来检索值。需要帮助来清除 foreach 中发生的错误循环。

public class State {
  public string Capital { get; set; }
  public int Population { get; set; }
  public int Size { get; set; }

  public State(string aCapital, int aPopulation, int aSize) {
    Capital = aCapital;
    Population = aPopulation;
    Size = aSize;
  } // Constructor of the class State

  public static Dictionary<string, State> GetStates() {
    Dictionary<string, State> myStates = new Dictionary<string, State>(); // need the () because its a class

    // myStates takes 2 values, one is a string , that is a state and State ,  which is inturn takes 3 values - 
    // Capital,Population, size

    State addStateCapital = new State("Montgomery", 214141, 244);
    myStates.Add("Alabama", addStateCapital);
    // second set
    addStateCapital = new State("Sacramento", 214141, 244);
    myStates.Add("California", addStateCapital);

    return myStates;
  }
}

我的主程序如下..但是我收到错误..

 var theState= State.GetStates();

 // this prints one item in a dictionary

 Console.WriteLine("State Capital of California is " +   theState["California"].Capital);

foreach (KeyValuePair<string,object> entry in theState)
{
    Console.WriteLine(entry.Key + " State Capital  is " +  entry.Value.ToString());
}

foreach 上出现错误:

Cannot convert keyvaluePair <string,DictionaryDemo.State> to System... Generic KVP<string,object>

需要帮助了解如何正确检索值。

最佳答案

1) 在KeyValuePair<,>中使用State而不是Object。 由于您已经在 State.GetStates() 返回类型中指定了

 Dictionary<string, State>

2) 同时将entry.Value.ToString()更改为entry.Value.Capital。因为它不会显示状态名称,而是显示类对象名称。因此,更改它 entry.Value.Capital

foreach (KeyValuePair<string,State> entry in theState)
 {
 Console.WriteLine(entry.Key + " State Capital  is " +  entry.Value.Capital);
 }

关于c# - 在 C# 中循环字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959767/

相关文章:

c# - 使用 LINQ 通过 Properties/reflection 将单个对象转换为 IEnumerable?

c# - c#.net 中用于 winforms 的气球类

python - 从 0-d numpy 数组中恢复字典

swift - 快速对两个值进行字典排序

C# For Loop with Random Int Generator 锁定程序

c# - 如何捕获导致应用程序冲突和终止的意外错误?

c# - 什么是 Environment.FailFast?

c# - Dictionary<string, List<IRp>> 问题,覆盖数据

c# - 如何制作 ToolStripComboBox 来填充 ToolStrip 上的所有可用空间?

c# - 区域设置 en-EN 是无效的文化标识符