Si8 Si8 - 25 days ago 6
C# Question

How to convert date to string and compare using Linq

Part of Sql Query:

...
RIGHT(cast([ADJ_DATE] AS DATE), 5) DH
...


Which returns the column as the following format in a DataTable (
dt
):

11-15
11-13
11-20
11-14


Trying to do the following:

string dat = DateTime.Now.AddDays(-2).ToString("MM-dd"); // which returns 11-13
var k = dt.AsEnumerable().Any(row => dat == Convert.ToString(row.Field<DateTime>("DH"))); //should return the row with 11-13, but instead I get an error


Error:

Exception Details: System.InvalidCastException: Specified cast is not valid.


How can I update the code so I get the desired result back.

Answer

You don't need the DateTime

var k = dt.AsEnumerable().Any(row => dat == row.Field<string>("DH")); 

The RIGHT

Returns the right part of a character string with the specified number of characters.

Please have a look here.

Update

If you want to get all the rows whose DH value is equal to dat then you should use the Where method:

var rows = dt.AsEnumerable().Where(row => dat == row.Field<string>("DH"));