Amr*_*ero 5 c# linq keyvaluepair
如何通过keyKeyValuePair的键获取值
我有一个 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"));
Run Code Online (Sandbox Code Playgroud)
为该列表创建一个循环:
foreach (var item in dataList) {
string key = item.Key;
string value = item.Value;
}
Run Code Online (Sandbox Code Playgroud)
我想做的是以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);
}
Run Code Online (Sandbox Code Playgroud)
或者也许可以通过索引获取值,例如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
}
Run Code Online (Sandbox Code Playgroud)
编辑2我尝试使用字典并向其中添加数据,例如:
dataList.Add("name", "john");
dataList.Add("name", "doe");
dataList.Add("age", "24");
Run Code Online (Sandbox Code Playgroud)
它说An item with the same key has already been added.,我认为因为我正在使用相同的密钥添加多个项目,"name"所以我需要这样做。
编辑3我想要实现的目标instead of how i try to do it:
我正在尝试循环遍历列表,并设置一个条件,如果具有关键路径文件的项目存在或不存在,如下所示:
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
我不能那样使用 item["path"] 的问题..我所能做的就是 item.Key 和 item.Value
foreach您只能通过所需的键运行查询:
foreach ( var item in dataList.Where( i => i.Key == "name" ) )
{
//use name items
}
Run Code Online (Sandbox Code Playgroud)
这使用 LINQ 仅包含KeyValuePairswhere Keyis "name"。您必须将using System.Linq其添加到源代码文件的顶部才能正常工作。