How to get previous closeset date from DataTable Using LinQ

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

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,

Thanks for your solution, however I am getting below error
String was not recognized as a valid DateTime.

Please look into this.

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,

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.