I have an excel sheet that contains different date ( Under different row).
I need to write an LinQ query which will give me closeset previous date. Suppose excel contains below date under Date Column
“15-11-2022”
“27-06-2022”
“23-06-2022”
“22-07-2022”
So if I pass input date as 25-06-2022, it should give me 3rd row that is “23-06-2022” as output.
Experts please help me
Yoichi
(Yoichi)
June 16, 2022, 9:48am
2
Hi,
Hope the following sample helps you.
dt.AsEnumerable.Select(Function(r) DateTime.ParseExact(r("Column").ToString,"dd-MM-yyyy",System.Globalization.CultureInfo.InvariantCulture)).OrderBy(Function(d) d).Where(Function(d) d<targetDate).Last.ToString("dd-MM-yyyy")
Sample20220616-2.zip (2.8 KB)
Regards,
Yoichi:
dt.AsEnumerable.Select(Function(r) DateTime.ParseExact(r("Column").ToString,"dd-MM-yyyy",System.Globalization.CultureInfo.InvariantCulture)).OrderBy(Function(d) d).Where(Function(d) d<targetDate).Last.ToString("dd-MM-yyyy")
Thanks for your solution, however I am getting below error
String was not recognized as a valid DateTime.
Please look into this.
Yoichi
(Yoichi)
June 16, 2022, 2:02pm
4
Hi,
Is there any non-datetime data (including empty)? If there is, can you try the following?
dt.AsEnumerable.Where(Function(r) DateTime.TryParseExact(r("Column").ToString,"dd-MM-yyyy",System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None,New DateTime)).Select(Function(r) DateTime.ParseExact(r("Column").ToString,"dd-MM-yyyy",System.Globalization.CultureInfo.InvariantCulture)).OrderBy(Function(d) d).Where(Function(d) d<targetDate).Last.ToString("dd-MM-yyyy")
Or, your data is recognized as datetime in excel, the following might work.
dt.AsEnumerable.Where(Function(r) DateTime.TryParse(r("Column").ToString,New DateTime)).Select(Function(r) DateTime.Parse(r("Column").ToString)).OrderBy(Function(d) d).Where(Function(d) d<targetDate).Last.ToString("dd-MM-yyyy")
Regards,
system
(system)
Closed
June 19, 2022, 2:02pm
5
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.