Gar*_*ghi 4 c# linq-to-objects c#-4.0
我有一个Dictionary<int int>.当我检查字典中的键的数字并且它在其中时,我希望它返回数字,否则我希望linq查询返回0.
像下面这样的东西,除了工作
var t = (from result in results
where result.Key == 3
select result.Key != null ? result.Value : 0).First();
Run Code Online (Sandbox Code Playgroud)
因为问题是当列表中没有数字时,序列不包含任何元素,因此您无法使用null或count进行检查.
只是用TryGetValue.
int i;
results.TryGetValue(3, out i);
Run Code Online (Sandbox Code Playgroud)
如果找到它,i则设置为该值.如果不是,i则默认为int,对于int将为零.
如果您想要除默认值之外的其他值,您可以这样做:
int i;
if (!results.TryGetValue(3, out i))
{
i = 5; // or whatever other value you want;
}
Run Code Online (Sandbox Code Playgroud)
如果你像我一样讨厌out参数样式,你可以创建一个扩展方法
public static class IDictionaryExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
T i;
dictionary.TryGetValue(key, out i);
return i;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话:
int i = dictionary.GetValueOrDefault(3);
Run Code Online (Sandbox Code Playgroud)
如果你想变得更加漂亮,你可以创建另一个扩展的oveload:
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
T i;
return dictionary.TryGetValue(key, out i) ? i : defaultValue;
}
Run Code Online (Sandbox Code Playgroud)
可以称之为
int i = dictionary.GetValueOrDefault(3, 5);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
421 次 |
| 最近记录: |