c# - 如何在 xml 数据的 linq 查询中使用 TryParse?

标签 c# xml linq

我在内存中处理每日股票市场数据的 xml,我得到其中一个日期的值“8/221/19055”。我看到 TryParse 可能是我检查有效日期的最佳选择,但 MSDN 文档似乎对第二个参数“out DateTime result”的解释很清楚。如何在下面的 linq 查询中使用它?

var makeInfo =
         from s in doc.Descendants("quote")
         where s.Element("LastTradeDate") != null
                && s.Attribute("symbol") != null
         let dateStr = s.Element("LastTradeDate").Value
         where !string.IsNullOrEmpty(dateStr)
                && DateTime.Parse(dateStr, enUS) == targetDate
         select new DailyPricingVolDP((string)s.Attribute("symbol"),
                                      (DateTime)s.Element("LastTradeDate"),
                                      (double)s.Element("Open"),
                                      (double)s.Element("DaysHigh"),
                                      (double)s.Element("DaysLow"),  
                                      (double)s.Element("LastTradePriceOnly"),
                                       (long)s.Element("Volume"));

最佳答案

Func<string, DateTime?> tryToGetDate =
        value =>
            {
                DateTime dateValue;
                return DateTime.TryParse(value, out dateValue) ? (DateTime?) dateValue : null;
            };

    var makeInfo =
         from s in doc.Descendants("quote")
         where s.Element("LastTradeDate") != null
                && s.Attribute("symbol") != null
         let dateStr = s.Element("LastTradeDate").Value
         let dateValue = tryToGetDate(dateStr)
         where dateValue != null && (DateTime)dateValue == targetDate
         select .... etc etc

关于c# - 如何在 xml 数据的 linq 查询中使用 TryParse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9003697/

相关文章:

C# Protractor - 在另一个元素中查找元素

asp.net - 用于存储应用程序设置的 web.config 和普通 xml 文件之间的区别

c# - System.Linq.Expressions.Expression<Func<TSource,TKey>> 中的 TKey 是什么?

linq - 将包含 'with' cte 的 sql 语句转换为 linq

c# - 使用导航属性的 LINQ 查询生成多个 SELECT 语句

c# - WPF 中的文件选择器对话框在哪里?

c# - 在远程机器上使用 Assembly.LoadFrom() 加载的程序集导致 SecurityException

c# - 如何编写 LINQ 查询以仅基于特定属性检索不同的记录?

php - simplexml_load_file() 有多快?

xml - 如何在 XPath 3 查询中引用其他 XML 文件