繁体   English   中英

从键值对获取一个条目

[英]Get a single entry from 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;
}

有没有一种方法可以不通过它获得类似的值

string content =  siteContent["contentText"].ToString();

谢谢

我假设siteContent是List<KeyValuePair<string,string>> ,所以您可以使用键“ contentText”选择键值对,并像这样获取它的值

string content =  siteContent.First(x=>x.Key=="contentText").Value;

您总是可以将List<KeyValuePair<string,string>>Dictionary<string,string> ,然后像使用它一样

var siteContentDict = siteContent.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
string content =  siteContentDict["contentText"];

您可以字典存储键值对,如果你已经使用字典那么就有可能获得关键的价值。

foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

siteContent可能是一个List<KeyValuePair<string,string>> ,我认为如果将其转换为Dictionary<string,string> ,则使用起来会更容易:

Dictionary<string, string> siteContentDict= siteContent.ToDictionary(s => s.Key, s => s.Value);
string content =  siteContentDict["contentText"];

您可以根据需要重复使用此字典,以轻松访问自己的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM