C# 如何迭代这种特定类型的字典<;int,结果>;?
我从数据库中得到了一系列结果,这些结果保存在C# 如何迭代这种特定类型的字典<;int,结果>;?,c#,.net,C#,.net,我从数据库中得到了一系列结果,这些结果保存在字典()中 我的成绩是: public int Id { get; set; } public string something { get; set; } public string somethingtwo { get; set; } public string somethingthree { get; set; } public DateTime Posted { get; set; } public string Location { get
字典()
中
我的成绩是:
public int Id { get; set; }
public string something { get; set; }
public string somethingtwo { get; set; }
public string somethingthree { get; set; }
public DateTime Posted { get; set; }
public string Location { get; set; }
public bool somethingfour { get; set; }
因此,字典
中有许多结果,我想对它们进行迭代。我该怎么做?我试过几种方法,但即使是我也知道它们行不通
我想这样做:
foreach(var result in resultDict)
{
mynewstring = result.Location;
mynewstringtwo = result.Posted;
// etc etc.
}
在上述代码中,kvp
是一个KeyValuePair
。您可以访问键
和值
属性,以获取字典
的整数键以及与该键
关联的结果
值。我将把它作为一个练习/猜谜游戏留给您,让您找出哪个属性是哪个!;-)
正如@Wiktor所提到的,您也可以访问字典的值
和键
集合来执行相同的操作,但可以检索一系列int
或值
属性
使用其他集合的备选方案:
foreach(var val in resultsDict.Values) {
// The key is not accessible immediately,
// you have to examine the value to figure out the key
UseResult(val); //val is a value.
}
foreach(var key in resultsDict.Keys) {
//The value isn't directly accessible, but you can look it up.
UseResult(resultsDict[key]);
UseKey(key);
}
这就是你需要的吗 您可以使用
Values
属性来迭代字典的值(另请参见)
代码示例:
// Your dictionary
var myResultDictionary = new Dictionary<int, Result>();
foreach (var item in myResultDictionary.Values)
{
// "item" holds a Result object
// Do something with item
}
// Your dictionary
var myResultDictionary = new Dictionary<int, Result>();
foreach (var item in myResultDictionary)
{
// "item" holds a KeyValuePair<int, Result> object
// You can access the value (a Result object) by calling "item.Value"
// Do something with item
}
您可以迭代Dictionary.Values,它与任何其他IEnumerable
或者,您可以迭代字典,它是一个IEnumerable
foreach(字典中的KeyValuePair项)
{
//做事
}
^^同样的事情,但是var动态地计算出它自己的类型
如果您只需要结果,也可以这样做:
foreach(var result in yourDictionary.Values)
{
Debug.WriteLine(result);
}
Dconditionary有一个名为Values的ValueCollection,因此代码为:
foreach (Result r in dict.Values)
{
mynewstring = result.Location;
mynewstringtwo = result.Posted;
}
使用字典上的
foreach(字典中的var keyValue)
{
//在这里使用键值
}
打得好。没想到。我想这就是我要找的。@Jason,是的,它确实有用,你没有读我例子后面的段落。我引述:“在上述代码中,kvp是KeyValuePair。您可以访问
键`和
值属性以获取字典的整数键以及与该键相关联的结果值非常感谢@Christopher,非常感谢。)第一种方式,我认为是正确的方式,是在我的问题的底部。当然,你问的时候它不在那里——我忘了添加我试过的内容,直到你问。
foreach (KeyValuePair<int,Result> item in dictionary)
{
//do stuff
}
foreach(KeyValuePair<int,result> keyValue in yourDictionary)
{
Debug.WriteLine(keyValue.Value);
//or
Debug.WriteLine(keyValue.Key);
}
foreach(var keyValue in yourDictionary)
{
Debug.WriteLine(keyValue.Value);
//or
Debug.WriteLine(keyValue.Key);
}
foreach(var result in yourDictionary.Values)
{
Debug.WriteLine(result);
}
foreach (Result r in dict.Values)
{
mynewstring = result.Location;
mynewstringtwo = result.Posted;
}