我需要根据值是否为浮点数将 linq 设置为 运行

I need to make linq to run depending on the value is floating point or not

我正在使用 XDocument 搜索大型 XML 文件。当用户寻找数值时,我得到的值为 decimal,我不区分整数和浮点值。我知道假设 XML 作为小数的输入是错误的,但如果不编写大量代码就无法构建 shorthand 逻辑。

用户在表单上输入要查找的值作为十进制,我通过在我的 SearchCriteria 对象中装箱将所有过滤器值保存为 属性。然后我使用下面的代码来查找匹配的元素:

IEnumerable<XElement> allNodes = xDoc.Root.Descendants(root);
allNodes = (from ex in allNodes 
    where ex.Descendants(fieldName)
        .Where(x => decimal.Parse(x.Value.Replace(".", ",")) == decimal.Parse(crit.SearchValue.ToString()))
        .Count() > 0 
    select ex);

并为邮政编码等字段获取异常,因为它不包含任何小数点。

我想做的是搜索所有值,不管它们是否包含小数点。但是为了完成这个任务,我需要有一个逻辑来决定是否在比较之前替换小数点。

如何在 LinQ 中完成?

此致。

只需重写条件:

ex
   .Descendants(fieldName)
   .Where(x => {
      decimal dec;
      return
         decimal.TryParse(x.Value, NumberStyles.Number, culture, out dec) &&
         /* other conditions and comparison with dec */;
}

如果无法解析值,则会将其忽略。

编辑: 使用特定区域性来解析数字。它会更快并且消耗更少的内存。还将已解析的 crit.SearchValue 存储在 lambda 之外。

不需要替换“.”通过一个“,”。您可以查询 decimal.Parse(s,NumberStyles.Any, new CultureInfo("en"),它会起作用。

您可以通过删除不需要重复的重复内容来提高代码效率:

IEnumerable<XElement> allNodes = xDoc.Root.Descendants(root);
decimal match = decimal.Parse(crit.SearchValue.ToString());
CultureInfo culture = new CultureInfo("en");
allNodes = (from ex in allNodes where ex.Descendants(fieldName)
    .Where(x => decimal.Parse(x.Value, culture) == match)
    .Count() > 0 select ex);