如何解决C#8:Linq Select,将字符串解析为Nullable Int
我正在尝试使用Linq select将字符串解析为Nullable int。以下最后一行在“选择”中不起作用。接收错误如下。怎么解决?
资源:https://stackoverflow.com/a/45066/13889515
var aviationInfo = _dbContext.Cpamlt
.Where(c=> c.Account == bppInfoRequestDto.AccountNumber)
.Select(cpamlt => new BppAviationInfoDto()
{
AccountNumberIdentityId = cpamlt.Cpamltid,SerialNumber = cpamlt.Vinserno,Manufacturer = cpamlt.Manmod,MakeModel = cpamlt.Manmak,YearManufactured = Int32.TryParse(cpamlt.Manyr,out tempVal) ? Int32.Parse(cpamlt.Manyr) : (int?)null,
错误:名称“ tempVal”在当前上下文中不存在
尽可能避免使用扩展方法
将Net Core 3.1与C#8一起使用
解决方法
如果以前没有使用过,则语法要求您定义变量。所以用
Int32.TryParse(cpamlt.Manyr,out int tempVal)
但是,您的代码可以缩短,因为tempVal
将包含您想要的值,您无需再次解析-
YearManufactured = Int32.TryParse(cpamlt.Manyr,out int tempVal) ? tempVal : (int?)null,
,
您可以创建一个新方法来包装此操作。
static int? NullableParse(string input)
{
int output = 0;
if (!int.TryParse(input,out output))
{
return null;
}
return output;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。