2016-11-15 51 views
0
SQL查詢的

部分比較:如何日期轉換爲字符串,並使用LINQ

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

它返回列作爲一個DataTable以下格式(dt):

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

爭取做以下:

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 

錯誤:

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

我該如何更新代碼才能得到想要的結果。

回答

2

你不需要DateTime

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

RIGHT

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

請看看here

更新

如果你想獲得所有那些DH值等於dat行,那麼你應該使用Where方法:

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

如果DH是一個DateTime列將失敗 – Steve

+0

我沒有回來。 – Si8

+0

@Steve既然'RIGHT'返回一個字符串如何'DH'可以'DateTime'列?我基於OP發佈的SQL來這麼說。 – Christos