c#列表 按键或索引获取价值[重复]

问题描述 投票:2回答:1

这个问题在这里已有答案:

如何通过键KeyValuePair获取值

我有一个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);
}

或者也许像Console.WriteLine(item[0].Value)一样得到指数值

我怎么能实现这个目标?

注意:我只需要使用一个foreach,不要为每个键使用分离的foreach。

编辑1如果我使用if(item.Key == "name") { // do stuff }我将无法使用其他键,如果声明,所以我需要在这个逻辑中工作:

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
}

编辑2我试图使用词典并向其添加数据,如:

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并且如果具有密钥路径文件的项目存在或者不是这样的条件:

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.Key&item.Value

c# linq keyvaluepair
1个回答
0
投票

您只能通过所需的键运行foreach查询:

foreach ( var item in dataList.Where( i => i.Key == "name" ) )
{
    //use name items
}

这使用LINQ只包括KeyValuePairs,其中Key"name"。您必须将using System.Linq添加到源代码文件的顶部才能使其正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.