简体   繁体   English

在C#中循环浏览字典

[英]Loop through a dictionary in C#

I have following code using class and dictionary that takes state and capital, but I'm unable to retrieve the values by looping through. 我有以下代码使用使用状态和大写的类和字典,但是我无法通过循环来检索值。 Need assistance is clearing up the error that occurs in foreach loop. 需要帮助来清除在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;
  }
}

and my Main program is as follows.. But I get error.. 而我的主程序如下。

 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());
}

ERROR on foreach : foreach错误:

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

Need help in understanding how to correctly retrieve the values. 在理解如何正确检索值方面需要帮助。

Your GetStates() method returns Dictionary<string, State> , so in this line 您的GetStates()方法返回Dictionary<string, State> ,因此在此行

var theState= State.GetStates();

the variable theState is assigned to type Dictionary<string, State> . 变量theState被分配为Dictionary<string, State> But in the following foreach block you try to access the values of the dictionary as KeyValuePair<string, object> . 但是在下面的foreach块中,您尝试以KeyValuePair<string, object>访问字典的值。

So you have to use it like this: 因此,您必须像这样使用它:

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

1) Use State instead of Object in KeyValuePair<,>. 1)在KeyValuePair <,>中使用State代替Object。 Since you have already specified specified in State.GetStates() return type has 由于您已经在State.GetStates()中指定了返回类型,因此具有

 Dictionary<string, State>

2) Also change the entry.Value.ToString() to entry.Value.Capital . 2)还将entry.Value.ToString()更改为entry.Value.Capital Since it will not show the State Name but the Class Object Name. 因为它不会显示状态名称,但会显示类对象名称。 Therefore, change it entry.Value.Capital 因此,将其更改为entry.Value.Capital

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

Changing the code snippet to below will solve your problem 将代码段更改为以下内容将解决您的问题

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

But to understand why you were getting that error, you may want to take a closer look of definition of Dictionary<TKey, TValue> which is derived from IEnumerable<KeyValuePair<TKey, TValue>> . 但是要了解为什么会出现此错误,您可能需要仔细看看Dictionary<TKey, TValue>的定义,该定义是从IEnumerable<KeyValuePair<TKey, TValue>>派生的。 So when you use foreach loop, internally it acts on IEnumerable<KeyValuePair<TKey, TValue>> . 因此,当您使用foreach循环时,它在内部作用于IEnumerable<KeyValuePair<TKey, TValue>> Here compiler expects each entity in foreach to be of type KeyValuePair<TKey, TValue> . 在这里,编译器期望foreach中的每个实体的类型为KeyValuePair<TKey, TValue> Now since in dictionary you have TValue is of type State that why compiler expects KeyValuePair<string, State> . 现在,由于在字典中您的TValue属于State类型,因此编译器为何期望KeyValuePair<string, State> Now to get in-depth understanding on this, you may want to go through "covariant and contravariant concepts c#" 现在,要对此有更深入的了解,您可能需要阅读“协变和反变概念c#”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM