簡體   English   中英

包含日期的字符串上的Linq Greater和Less Than運算符

[英]Linq Greater and Less Than operator on string containing date

我正在我的應用程序中編寫一個linq查詢,我想使用“小於”運算符。 但是我試圖將其應用於列的類型是字符串(我們無法更改)並導致intellisense拋出錯誤,因為“<”運算符不能用於字符串類型。

我的問題是我怎么能這樣做? 以下是我的代碼中發生錯誤的部分。

public ActionResult Index()
{
    var results = Mapper.Map<IEnumerable<VesselViewModel>>(db.tbl_vessels
    .Where(p => 
          (p.vessel_type.Contains("AHTS")) &&
          (p.spotlist_id == 2) &&
          (p.fixture_start <= System.DateTime.Now.Date)
     )
    .ToList());
    return View(results);
}

fixture_start是一個字符串,由於其他地方的復雜性,我們無法改變它。 反正這個問題呢?

如果p.fixture_start是包含日期的字符串,那么您必須在比較之前解析它:

(p => DateTime.Parse(p.fixture_start) <= System.DateTime.Now.Date)

即使您無法更改fixture_start的類型,也可以將其解析為DateTime,僅用於查詢:

(DateTime.Parse(p.fixture_start) <= System.DateTime.Now.Date)

這不是一個選擇嗎?

好吧,解決方案可能是使用Linq to Entities執行部分查詢並使用Linq to Objects結束查詢,您可以將string轉換為DateTime

var results = Mapper.Map<IEnumerable<VesselViewModel>>(db.tbl_vessels
             .Where(p => 
                   (p.vessel_type.Contains("AHTS")) &&
                   (p.spotlist_id == 2))
             .AsEnumerable()// This should make the trick
             .Where(p => DateTime.Parse(p.fixture_start) <= System.DateTime.Now.Date)
             .ToList());

如果fixture_date是一個字符串。 您應該將它與字符串進行比較。 如果這是在數據庫中存儲為字符串的日期,則應將其存儲為yyyymmdd。 如果是這種情況,那么您可以將其與以相同方式格式化的當前日期進行比較。 您將能夠使用少於比較兩個字符串。

p.fixture_date <= System.DateTime.Now.ToString("yyMd") // not sure this format is correct

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM