繁体   English   中英

如何在Linq中测试字符串是否可以转换为小数?

[英]How can I test if a string can be converted to a decimal in Linq?

我正在尝试使用Linq to XML从XML提取一些数据,并且我有以下代码:

            commisionPct = XDocument.Parse(commissionXml)
                                    .Descendants("Range")
                                    .Attributes("commission")
                                    .Select(x => Convert.ToDecimal(x.Value))
                                    .FirstOrDefault();

问题是如果x.Value不是小数,我不希望它出现异常。 通常我会使用decimal.TryParse但是我不确定在linq语句中执行此操作的干净方法。 我想我可以用try / catch块包围它,但是我很好奇在Linq中是否有更好的方法可以做到这一点。

如果不是十进制,我希望它返回十进制默认值(0)。

像这样更改您的Select

//Linq
.Select(
    x =>
    {
         Decimal d;
         Decimal.TryParse(x.Value, out d);
         return d;
    })
.FirstOrDefault();

或者,创建一种为您处理的方法。

//Linq
.Select(x => DecimalTryParseOrZero(x.Value))
.FirstOrDefault();

Decimal DecimalTryParseOrZero(String input)
{
    Decimal d;
    Decimal.TryParse(x.Value, out d);
    return d;
}

您可以使用TryParse并使它以可为空的十进制形式返回结果:

.Select(x => {
  decimal n;
  return Decimal.TryParse(x.Value, out n) ? n : (decimal?)null
})

您仍然可以使用decimal.TryParse 这是一个简单的例子:

var strings = new List<string> { "1", "2", "3", "4", "cow", 
                                 "duck", "23", "42", "linq" };

decimal d = 0;
var nums = from x in strings
           select decimal.TryParse(x, out d) ? d : 0;

将您的示例与方法语法一起使用,它将看起来像这样:

decimal d = 0;
commisionPct = XDocument.Parse(commissionXml)
                        .Descendants("Range")
                        .Attributes("commission")
                        .Select(x => decimal.TryParse(x, out d) ? d : 0)
                        .FirstOrDefault();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM