gpt4 book ai didi

c# - 如何迭代这种特定类型的 Dictionary

转载 作者:太空狗 更新时间:2023-10-30 00:15:52 25 4
gpt4 key购买 nike

我有一堆来自数据库的结果,保存在 Dictionary<int, Result>() 中.

我的结果类是:

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

因此,Dictionary<int, Result>里面有很多结果,我想遍历它们。我该怎么做?我尝试了几种方法,但即使我也知道它们行不通。

我想做这样的事情:

foreach(var result in resultDict)
{
mynewstring = result.Location;
mynewstringtwo = result.Posted;
// etc etc.
}

最佳答案

foreach(var kvp in resultsDict) {
//Do somethign with kvp
UseResult(kvp.Value); //kvp.Value is a Result object
UseKey(kvp.Key); //kvp.Key is the integer key you access it with
}

在上面的代码中kvpKeyValuePair<int, Result> .您可以访问 KeyValue属性以获取 Dictionary 的整数键和 Result与此相关的值 Key .我会把它留作练习/猜谜游戏,让您找出哪个属性是哪个! ;-)

正如@Wiktor 提到的,您还可以访问字典的 ValuesKeys集合做同样的事情,但检索 int 的序列或 Value属性代替。

使用其他集合的替代方案:

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

关于c# - 如何迭代这种特定类型的 Dictionary<int, Result>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10708313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com