我从一年前开始使用VB.NET,现在我必须使用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
Run Code Online (Sandbox Code Playgroud)
在C#中执行此操作的最佳方法是什么?
我发现了这样的东西,但我不知道是否是最好的方法来做到这一点..
Person oPerson = dictionary.Where(z => z.Key == key).FirstOrDefault().Val
Run Code Online (Sandbox Code Playgroud)
可能是这样的:
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
}
Run Code Online (Sandbox Code Playgroud)