Datatable - 从字符串类型列获取max(date) [英] Datatable - Get max(date) from string type column

查看:1002
本文介绍了Datatable - 从字符串类型列获取max(date)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据的结果在c#_

I have this datatable result in c#

DAY      Employee Job1   Job2   Job3
1/1/2012    a    1      1      1 
1/1/2012    b    2      2      2
1/1/2012    c    2      1      4
1/1/2012    d    4      2      1
1/2/2012    a    3      2      5
1/2/2012    b    2      2      2
1/2/2012    c    3      3      3
1/2/2012    d    1      1      1
1/3/2013    a    5      5      5
1/3/2013    b    2      2      6
1/3/2013    c    1      1      1
3/13/2013   d    2      3      4
2/1/2013    a    2      2      2
2/1/2013    b    5      5      2
2/7/2013    c    2      2      2
2/5/2013    a    3      3      3
3/2/2013    b    2      3      3
2/1/2013    a    4      4      2

现在我想从第一列(MM / dd / yyyy)中找到最大日期,应为3/13/2013。另请注意,此列是字符串数据类型。

Now i want to find the max date from the first column(MM/dd/yyyy) which should be 3/13/2013. Also note that this column is of string datatype.

请问有人可以建议我如何使用c#中的Linq,还是有一个简单的方法?

Please, can anybody suggest me how to do this with "Linq" in c# or is there a simple way to do this?

推荐答案

使用 DateTime.Parse DateTime.ParseExact 将字符串解析为数据时间。这应该工作:

Use DateTime.Parse or DateTime.ParseExact to parse a string to a datatime. This should work:

DateTime maxDate = table.AsEnumerable()
    .Max(r => DateTime.Parse(r.Field<string>("DAY")));

但是,为什么首先是字符串?

However, why is it a string in the first place?

编辑
您还应该考虑用于创建此字符串的文化。您必须在分析字符串时再次使用这种文化。

Edit You should also take the culture into account which was used to create this string. You have to use this culture again when you parse the string.

所以这个结果适用于不同的文化,但结果是不同的,你可以在这里看到:

So this results works for different cultures but the result is different as you can see here:

System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
DateTime maxDate = table.AsEnumerable()
    .Max(r => DateTime.Parse(r.Field<string>("DAY")));
Console.WriteLine(maxDate);
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("de-DE"); // germany
maxDate = table.AsEnumerable()
    .Max(r => DateTime.Parse(r.Field<string>("DAY")));
Console.WriteLine(maxDate);

这篇关于Datatable - 从字符串类型列获取max(date)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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