LINQ无法在特定列排序依据日期? [英] LINQ unable to OrderBy date in specific column?

查看:105
本文介绍了LINQ无法在特定列排序依据日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是这样的一个CSV文件:

I have a CSV file which goes like this:

1,01/01/2001,a
2,19/09/2013,as
3,12/05/2016,asd
4,13/05/2016,asdf
5,12/12/2012,asdfg
6,05/02/2006,asdfgh
7,06/03/2011,asdfghj

我要排序和按时间顺序显示的日期,但我似乎无法让我的code梳理出来。然而,我的code是能够根据CSV文件格式来显示日期。

I want to sort and display the dates in chronological order but I can't seem to get my code to sort it out. However, my code is able to display the dates according to the format in the CSV file.

如果CSV文件是这样的:

If the CSV file is like this:

01/01/2001
19/09/2013
12/05/2016
13/05/2016
12/12/2012
05/02/2006
06/03/2011

然后,它工作得很好。

Then, it works just fine.

以下是我的code:

string parts = new StreamReader(@"C:\input.txt").ReadToEnd();
string[] file = parts.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();

for (int i = 0; i < file.Length; i++)
{
    string[] data = file[i].Split(new string[] { "," }, StringSplitOptions.None);
    string[] dates = new string[] { data[1].ToString() };
    //var date = dates.OrderBy(x => DateTime.Parse(x)).ToList();
    var date = dates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));

    foreach (string s in date)
    {
        sb.AppendLine(s + "<br />");
        Label1.Text = sb.ToString();
    }
}

我已经测试了使用这两种 DateTime.Parse DateTime.ParseExact CSV文件这个code ,但他们没有工作。

I have tested this code using both DateTime.Parse and DateTime.ParseExact on the CSV file, but they didn't work.

我是真正的新LINQ查询,这使用它是我的第一次。我真的AP preciate它是否有提供有什么错我的code的解释。

I'm really new to LINQ query and this is my first time using it. I would really appreciate it if there is an explanation provided on what's wrong with my code.

推荐答案

您要排序的数组(日期)总是包含一个日期(因为你创建它每次从在循环中的一行)。然后添加此行到标签的文本。

You are sorting an array (dates) that always contains one date (because you create it each time from a single line in a loop). Then you add this line to the label's text.

您必须创建一个包含所有的日期,你理清之前的集合。

You have to create a collection that contains all the dates, before you sort it.

string parts = new StringReader(@"C:\input.txt").ReadToEnd();
string[] lines = parts.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
List<string> dates = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
    string[] data = lines[i].Split(new string[] { "," }, StringSplitOptions.None);
    dates.Add(data[1]);
}

var datesSorted = dates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in datesSorted)
{
    sb.AppendLine(s + "<br />");
}

Label1.Text = sb.ToString();

这篇关于LINQ无法在特定列排序依据日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆