2013-08-02 25 views
0

我與VB.NET的工作,因爲一年前,現在我在用C#另一個項目的工作,我無法找到這個等價..Dictionary.Item在C#

在VB.NET

Dim dictionary As Dictionary(Of String, Decimal) 
Dim oPerson As Person = Nothing 
Dim key as string = "SomeValue" 

If dictionary.ContainsKey(key) Then 
oPerson = dictionary.Item(key) 
End If 

什麼是在C#中做到這一點的最佳方法?

我發現這樣的事情,但我不知道,如果是做的最好的方法..

Person oPerson = dictionary.Where(z => z.Key == key).FirstOrDefault().Val 
+0

您是否嘗試過使用在線代碼轉換器從VB到C# –

+0

您只是試圖從字典中使用某個鍵來查找值是否正確? – adityaswami89

+1

http://www.developerfusion.com/tools/convert/vb-to-csharp/試試這個鏈接 –

回答

2
Dictionary<string, decimal> dictionary = null; 
Person oPerson = null; 
string key = "SomeValue"; 

if (dictionary.ContainsKey(key)) { 
    oPerson = dictionary[key]; 
} 
Dictionary<string, decimal> dictionary = null; 
Person oPerson = null; 
string key = "SomeValue"; 

if (dictionary.ContainsKey(key)) { 
oPerson = dictionary[key]; 
} 
+0

'oPerson'是一個'Person',但你正試圖給這個變量賦予'decimal'。此外'字典'不應該'null' –

4

可能是這樣的:

Dictionary<String, Person> dictionary = new Dictionary<String, Person>(); 

... 

Person oPerson = null; 
String key = "SomeValue"; 

if (dictionary.TryGetValue(key, out oPerson)) { 
    // Person instance is found, do something with it 
} 
0

詞典dictobj =新詞典(); dictobj.Add(1,123); dictobj.Add(2,345);

 var a = dictobj.Where(x => x.Key == 1).First().Value; 
+1

這是完全相同的OP目前有什麼 – Sayse

0

OP答案几乎是已經存在,如果他可以使用LINQ來獲取數據。因爲條件只有一個關鍵,所以在條件足夠的情況下,否則您可以使用.Contains獲取多個條件。

Person oPerson =new Person();  
var a= dictionary.Where(z => z.Key == key).FirstOrDefault(); 
if (a.Count() > 0) 
{ 
    oPerson.ABC = a.FirstOrDefault().Value; 
} 
0

有兩種方法可以解決這個:

這將拋出一個異常,如果該鍵不存在於字典(例外是不是一件壞事!)

var value = dictionary["key"] as Person; 

如果你想檢查鑰匙是否先存在:

Person person = null; 
if(!dictionary.TryGetValue("key", out person)) 
{ 
    //Dictionary did not contain value, act accordingly ... 
    // ... 
} 

我想強調異常並不是一件壞事,如果你的應用程序如果字典不包含Person,那麼以後會失敗,那麼通過一切手段拋出異常!