【发布时间】:2018-03-01 10:12:11
【问题描述】:
如何通过key为keyKeyValuePair获取value
我有一个List<KeyValuePair<string, string>>
var dataList = new List<KeyValuePair<string, string>>();
// Adding data to the list
dataList.Add(new KeyValuePair<String, String>("name", "foo"));
dataList.Add(new KeyValuePair<String, String>("name", "bar"));
dataList.Add(new KeyValuePair<String, String>("age", "24"));
为该列表创建一个循环:
foreach (var item in dataList) {
string key = item.Key;
string value = item.Value;
}
我想做的是以某种方式获得string name = item["name"].Value:
foreach (var item in dataList) {
// Print the value of the key "name" only
Console.WriteLine(item["name"].Value);
// Print the value of the key "age" only
Console.WriteLine(item["age"].Value);
}
或者也许通过 Index 获得 Value,例如 Console.WriteLine(item[0].Value)
我怎样才能做到这一点?
注意: 我只需要使用一个 foreach,而不是为每个键使用单独的 foreach。
编辑 1 如果我使用 if(item.Key == "name") { // do stuff } 我将无法使用该 if 语句中的其他键,所以我需要按照这个逻辑工作:
if(item.Key == "name") {
// Print out another key
Console.WriteLine(item["age"].Value)
// and that will not work because the if statment forced to be the key "name" only
}
Edit 2 我尝试使用 Dictionary 并向其中添加数据,例如:
dataList.Add("name", "john");
dataList.Add("name", "doe");
dataList.Add("age", "24");
上面写着An item with the same key has already been added.,我想是因为我要使用相同的键"name" 添加多个项目,我需要这样做。
编辑 3 我要达到的目标instead of how i try to do it:
我正在尝试遍历 List 并确定是否存在带有关键 path 文件的项目,如下所示:
if(File.Exists(item["path"]) { Console.WriteLine(item["name"]) }
// More Explained
foreach (var item in dataList) {
if (File.Exists(//the key path here//)) {
MessageBox.Show("File //The key name here// exists.");
}else {
MessageBox.Show("File //The key name here// was not found.");
}
}
我不能那样使用 item["path"] 的问题.. 我能做的就是 item.Key & item.Value
【问题讨论】:
-
你有一个
List而不是Dictionary<string, string>有什么原因吗?您的按键搜索用例使您看起来实际上并不需要该列表。 -
你能举一个使用
Dictionary<string, string>的例子吗,因为我试过用它,但它说有更多的项目有相同的键?我想拥有多个具有相同密钥的项目。如果可以的话,我的问题将得到解决。 -
在这一点上,这看起来真的很像XY problem。你为什么不退后一步,准确地解释你想做什么 而不是 你是怎么做的?
-
我已经更新了问题,请问您可以阅读 Edit 3 部分吗?
-
键名是灵活的还是固定的?
标签: c# linq keyvaluepair