0

I have found a few threads that have dealt with this issue. Though, they are not in a context that is usefull for me. Pretty much, I am trying to convert a DateTime to string, for rendering it into a MVCContrib Grid. Here is how things look inside of my model:

public IQueryable<FindStudentViewModel> GetStudentsProjected()
    {
        var projectedStudents= from p in FindAllStudents()
                                select new FindStudentViewModel
                                {
                                    StudentID = p.StudentID,
                                    FirstName = p.FirstName,
                                    LastName = p.LastName,
                                    EmailAddress = p.EmailAddress,
                                    CurrentCollege = p.CurrentCollege,
                                    IAUTerm = p.IAUTerm,
                                    IAUProgram = p.IAUProgram,
                                    InquirySource = p.InquirySource,
                                    InquiryDate = (string)p.InquiryDate.ToString(),
                                    Status = p.Status

                                };

        return projectedStudents;
    }

And of course, LINQ does not like this one bit. Pretty much, I need to be able to convert the InquiryDate into a string, and then order the results by InquiryDate. Thank you in advance.

4

1 回答 1

2

Ordering on a string representation of a DateTime might not be a very good plan. Consider the following dates:

5/4/2007
9/12/2011
6/4/1904

If you order them when they are DateTime type, you'll get:

6/4/1904
5/4/2007
9/12/2012

If you use .ToString() on them, then order on it, you'll get:

5/4/2007
6/4/1904
9/12/2011

Code to test with:

var dates = new DateTime[] { new DateTime(2012, 9, 12), new DateTime(1904, 6, 4), new DateTime(2007, 5, 4) };
foreach (var item in dates.OrderBy(d => d))
{
    Console.WriteLine(item);
}

Console.WriteLine();
var temp = dates.Select(d => d.ToString());
foreach (var item in temp.OrderBy(d => d))
{
    Console.WriteLine(item);
}
于 2012-09-27T18:35:37.977 回答