我需要让linq运行,具体取决于值是浮点还是不浮点数

时间:2015-02-24 12:17:18

标签: c# xml linq linq-to-xml

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

用户输入要在表单上搜索的值为十进制,并通过装箱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中完成?

问候。

2 个答案:

答案 0 :(得分:3)

无需更换&#34;。&#34;通过&#34;,&#34;。您可以查询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);

答案 1 :(得分:2)

只需重写条件:

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

如果无法解析值,则忽略它。

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