按键从字典中删除并检索值

Mas*_*ash 8 .net c# dictionary

有没有办法从Dictionary(通过Key)中删除条目并Value在"同一步骤"中检索它?

例如,我正在打电话

Dictionary.Remove(Key);
Run Code Online (Sandbox Code Playgroud)

但我也希望同时返回Value.该函数只返回一个bool.

我知道我可以做点什么

Value = Dictionary[Key];
Dictionary.Remove(Key);
Run Code Online (Sandbox Code Playgroud)

但似乎这会搜索字典两次(一次获取值,另一次将其从字典中删除).我怎么能(如果可能的话)两次搜索字典?

vul*_*ven 6

从 .NET Core 2.0 开始,我们有:

public bool Remove (TKey key, out TValue value);

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.remove?view=netcore-2.0#System_Collections_Generic_Dictionary_2_Remove__0__1__

请注意,此 API 尚未包含在 .NET Standard 2.0.NET Framework 4.7 中

  • 但是,它*包含在 [.NET Standard 2.1(预览版)](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.remove?view =网络标准-2.1) (2认同)