我有以下代码:
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 值转换回元组。
如何将键值存储在列表中,以便我可以使用 lambda 来查询它,例如通过键?
所有这些代码:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句