簡體   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