Reputation: 765
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
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.
Please, can anybody suggest me how to do this with "Linq" in c# or is there a simple way to do this?
Upvotes: 1
Views: 2850
Reputation: 460238
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);
Upvotes: 2
Reputation: 581
Formatting between programs can be annoying even if they are made by the same company. This thread is similar and hopefully will point you in the right direction:
DateTime format mismatch on importing from Excel Sheet
if you've confirmed it's a String
, then have you tried a simple:
DateTime dt = Convert.ToDateTime(date);
?
Upvotes: 0