2 回答

TA貢獻1875條經(jīng)驗 獲得超5個贊
不幸的是,你不能這樣做。Dictionary<TKey, TValue>公開一個方法是完全合理的bool TryGetEntry(TKey key, KeyValuePair<TKey, TValue> entry),但它并沒有這樣做。
正如評論中所建議的那樣,最簡單的方法可能是使字典中的每個值都具有與字典中的鍵相同的鍵。所以:
var dictionary = new Dictionary<string, KeyValuePair<string, int>>(StringComparer.OrdinalIgnoreCase)
{
// You'd normally write a helper method to avoid having to specify
// the key twice, of course.
{"abc1", new KeyValuePair<string, int>("abc1", 1)},
{"abC2", new KeyValuePair<string, int>("abC2", 2)},
{"abc3", new KeyValuePair<string, int>("abc3", 3)}
};
if (dictionary.TryGetValue("Abc2", out var entry))
{
Console.WriteLine(entry.Key); // abC2
Console.WriteLine(entry.Value); // 2
}
else
{
Console.WriteLine("Key not found"); // We don't get here in this example
}
如果這是類中的一個字段,您可以編寫輔助方法以使其更簡單。您甚至可以編寫自己的包裝類Dictionary來實現(xiàn)IDictionary<TKey, TValue>但添加一個額外的TryGetEntry方法,以便調用者永遠不需要知道“內(nèi)部”字典的樣子。

TA貢獻1877條經(jīng)驗 獲得超1個贊
即使大小寫與鍵不匹配,您也可以使用以下利用 LINQ 的代碼來獲取字典鍵值對。
注意:此代碼可用于任何大小的字典,但它最適合較小大小的字典,因為 LINQ 基本上是一一檢查每個鍵值對,而不是直接轉到所需的鍵值對。
Dictionary<string,int> dictionary1 = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
{"abc1",1},
{"abC2",2},
{"abc3",3}
} ;
var value1 = dictionary1["ABC2"];//this gives 2, even though case of key does not macth
//use LINQ to achieve your requirement
var keyValuePair1 = dictionary1.SingleOrDefault (d => d.Key.Equals("Abc2", StringComparison.OrdinalIgnoreCase) );
var key1 = keyValuePair1.Key ;//gives us abC2
var value2 =keyValuePair1.Value;//gives us 2
- 2 回答
- 0 關注
- 289 瀏覽
添加回答
舉報