查询List <string>中的键值

时间:2018-01-17 10:56:18

标签: c#

我有以下代码:

var tuple = new Tuple<string, string>("MyKey", "MyValue");
var list = new List<string>();
var str = tuple.ToString();
list.Add(str);
// str has the value "(MyKey, MyValue)"

我有一个预定义的对象,我需要使用字符串列表 我决定使用一个元组,但我不确定如何将str值转换回元组。

如何在List中存储键值,以便我可以使用lambda来查询它,例如靠钥匙?

3 个答案:

答案 0 :(得分:2)

所有这些代码:

var tuple = new Tuple<string, string>("MyKey", "MyValue");
var list = new List<string>();
var str = tuple.ToString();
list.Add(str);
// str has the value "(MyKey, MyValue)"

可以替换为字典:

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("MyKey", "MyValue");

然后,如果您愿意,可以使用linq查询字典:

value = values.Where(x => x.ContainsKey("MyKey"));

您可以按如下方式获取包含所有键的列表:

List<string> keys = values.Keys;

因此无需为此单独列出。

如果你想要一个包含两个以逗号分隔的值的字符串列表,那么字典也会这样做:

List<string> keysValues = (from item in values
                                               select item.Key + "," + item.Value).ToList();

答案 1 :(得分:1)

使用词典。

var dictionary = new Dictionary<string, string>();
        dictionary.Add("myKey", "myVal");

        if (dictionary.ContainsKey("myKey"))
            dictionary["myKey"] = "myVal1";

答案 2 :(得分:-1)

我建议您使用Dictionary。但如果你真的需要这样做:

要从$label-md-text-color-focused: red; 转换回string(假设Key本身永远不会包含commma + space):

Tuple