简体   繁体   English

DateTime.TryParse实现问题

[英]DateTime.TryParse implementation issue

I have this code where I need to determine if the received value is DateTime, if so, return 0 otherwise return the value in order to calculate sum: 我在需要确定接收的值是否为DateTime的地方有此代码,如果是,则返回0,否则返回该值以便计算总和:

row["Total"] = months.Sum(kv =>
                            {
                                DateTime dateValue;
                                if (!DateTime.TryParse(kv.Value, out dateValue))
                                {
                                    return double.Parse(kv.Value);
                                }
                                else
                                {
                                    return 0;
                                }
                            });

but these values are being treated as DateTime as well? 但是这些值也被视为DateTime吗?

1726.07

4756.06

1.08

1.27

1.11

will every double value be treated as DateTime then? 那么每个双精度值都将被视为DateTime吗?

What if you do it 'all the way around' : 如果“一路走来”怎么办:

row["Total"] = months.Sum(kv =>
                            {
                                double toReturn = 0;
                                if (!Double.TryParse(kv.Value, out toReturn )) return 0;

                                return toReturn;            
                            });

Sometimes double values can be parsed using DateTime.Parse but i don't believe you can parse date like "22/06/2015" to double. 有时可以使用DateTime.Parse解析双精度值,但我不相信您可以将“ 22/06/2015”之类的日期解析为双精度。 And you don't really need this 'else' statement. 而且您实际上并不需要此“ else”语句。

Other option would be to use DateTime.TryParseExact and specify format for your date... 其他选择是使用DateTime.TryParseExact并指定日期格式...

You can try this.. 你可以试试看

DateTime dateValue;
months.Where(kv=>(!DateTime.TryParse(kv.Value, out dateValue))).Sum(kv =>double.Parse(kv.Value));//Sum of values where values are not datetime

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

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