简体   繁体   中英

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

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

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> :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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