[英]Get a single entry from keyvaluepair
Hi all I have a class where I create a keyvaluepair. 大家好,我有一个我在其中创建键值对的类。
if (reader.HasRows)
{
reader.Read();
string content = reader["ContentText"].ToString();
siteContent.Add(new KeyValuePair<string,string>("contentText",content));
siteContent.Add(new KeyValuePair<string,string>("pageTitle",reader["PageTitle"].ToString()));
siteContent.Add(new KeyValuePair<string,string>("meta",reader["Meta"].ToString()));
siteContent.Add(new KeyValuePair<string, string>("menuId", reader["MenuId"].ToString()));
siteContent.Add(new KeyValuePair<string, string>("cssFile", reader["CssFile"].ToString()));
siteContent.Add(new KeyValuePair<string, string>("accessLevel", reader["AccessLevel"].ToString()));
return siteContent;
}
is there a way without looking through it to get a value something like 有没有一种方法可以不通过它获得类似的值
string content = siteContent["contentText"].ToString();
Thanks 谢谢
I assume siteContent is List<KeyValuePair<string,string>>
, so you can select keyvaluepair with key "contentText" and get it's value like this 我假设siteContent是List<KeyValuePair<string,string>>
,所以您可以使用键“ contentText”选择键值对,并像这样获取它的值
string content = siteContent.First(x=>x.Key=="contentText").Value;
You can always store your List<KeyValuePair<string,string>>
as Dictionary<string,string>
and then use it like 您总是可以将List<KeyValuePair<string,string>>
为Dictionary<string,string>
,然后像使用它一样
var siteContentDict = siteContent.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
string content = siteContentDict["contentText"];
You can Dictionary to store key value pair and get the value of key if you are already using dictionary then it is possible. 您可以字典存储键值对,如果你已经使用字典那么就有可能获得关键的价值。
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
siteContent
is probably a List<KeyValuePair<string,string>>
, i think it would be easier for you to use it if you convert it as a Dictionary<string,string>
: siteContent
可能是一个List<KeyValuePair<string,string>>
,我认为如果将其转换为Dictionary<string,string>
,则使用起来会更容易:
Dictionary<string, string> siteContentDict= siteContent.ToDictionary(s => s.Key, s => s.Value);
string content = siteContentDict["contentText"];
You reuse this dictionary as you like to easily access to your values. 您可以根据需要重复使用此字典,以轻松访问自己的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.