简体   繁体   English

无法将日期时间转换为字符串

[英]Cannot convert datetime to string

I have a database with some dates, i want to fetch them and convert them into a string[] to use in a graph. 我有一个带有某些日期的数据库,我想获取它们并将它们转换为string []以在图形中使用。

        var Yaxis = db.Graphs
                    .Where(x => x.Node.Contains(Node))
                    .Select(x => x.Dates)
                    .ToArray();


        var data = new string[Yaxis.Length];
        for (int i = 0; i < Yaxis.Length ; i++)
        {
            data[i] = Yaxis[i].ToString;
        }

The .ToString do not work here with a "non-delegate type"-error. .ToString不适用于“非代理类型”错误。 I dont know any other way to parse the array to a string[]. 我不知道将数组解析为字符串[]的任何其他方法。

Any idea? 任何想法?

data[i] = Yaxis[i].ToString();

When you don't include the parentheses, the compiler will assume you're talking about the function ToString , when you're actually talking about the return value. 当您不包括括号时,编译器将假定您实际上是在谈论函数 ToString ,而实际上是在谈论返回值。

When you're talking about the function itself, it's called a delegate (kind of similar to a function pointer in C/C++), which explains the error you're getting. 当您谈论函数本身时,它称为委托(类似于C / C ++中的函数指针),它说明了您遇到的错误。

As Antonijn posted, the immediate problem is that you're using ToString without actually calling the method. 正如Antonijn发布的那样,直接的问题是您在使用ToString而不实际调用该方法。

However, you can do better than this to start with by doing it in LINQ: 但是,从LINQ开始,您可以做得更好:

var data = db.Graphs
             .Where(x => x.Node.Contains(Node))
             .Select(x => x.Dates.ToString())
             .ToArray();

Note that we're calling ToString() in the projection here. 请注意,我们在此处的投影中调用ToString() If that doesn't give the result you want (eg because it performs the conversion in the database) you can split it into two Select calls, with an AsEnumerable call forcing the second one to execute locally: 如果没有得到您想要的结果(例如,因为它在数据库中执行了转换),则可以将其分为两个Select调用,使用AsEnumerable调用强制第二个在本地执行:

var data = db.Graphs
             .Where(x => x.Node.Contains(Node))
             .Select(x => x.Dates)
             .AsEnumerable()
             .Select(x => x.ToString())
             .ToArray();

This will use the default string representation of DateTime in the current culture, of course. 当然,这将使用当前区域性中的默认DateTime字符串表示形式。 You may want to consider specifying a standard or custom date/time format string to change the output format, and maybe even a different culture... it depends on what you're going to do with the data. 您可能要考虑指定标准自定义的日期/时间格式字符串以更改输出格式,甚至可能是不同的区域性...这取决于您要对数据进行的处理。

All of this assumes that you don't need Yaxis for anything else. 所有这些假设都假定您不需要Yaxis If you do need Yaxis , you can still use LINQ to simplify your code: 如果确实需要Yaxis ,仍然可以使用LINQ来简化代码:

var data = Yaxis.Select(x => x.ToString()).ToArray();

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

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