【发布时间】:2014-01-28 11:23:00
【问题描述】:
KeyValuePair<string, int> 的默认值是多少?
例如我正在运行 LINQ 查询并从中返回 FirstOrDefault() 值
KeyValuePair<string, int> mapping = (from p in lstMappings
where p.Key.Equals(dc.ColumnName, StringComparison.InvariantCultureIgnoreCase)
select p).FirstOrDefault();
if (mapping != null)
{
}
如何检查mapping 对象是否为空/空白
(我在上面的代码中遇到编译时错误Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<string,int>' and '<null>')
PS:lstMappings 属于类型
List<KeyValuePair<string, int>>
【问题讨论】:
-
LINQ 查询的使用非常糟糕。你根本不应该在那里使用 LINQ。如果您希望能够以不区分大小写的方式处理您的密钥,您应该提供自己的 IEqualityComparer 来做到这一点。然后,您只需使用 Dictionary 的 ContainsKey 方法来确定是否存在匹配项,如果存在,则通过该键获取值。