簡體   English   中英

在linq搜索中使用int.parse(string)不起作用

[英]Using int.parse(string) in linq search doesn't work

我在C#中使用LINQ搜索。 我的搜索之一需要將string轉換為int 當我嘗試使用int.parse()convert.toInt32() ,它顯示錯誤(在LINQ中無法識別)

例如:

var google = from p in ctx.dates
       where int.Parse(p.effDate) < 20101212 && int.Parse(p.effDate) > 20121212
           select p;

如您所見,我有一個字符串,其中包含yyyymmdd格式的日期,我想將其轉換為整數,以便在這些日期之間進行搜索。

yyyyMMdd格式具有很好的屬性,即字典順序與時間順序相同,因此您可以使用字符串比較:

var google = from p in ctx.dates
             where p.effDate.CompareTo("20121212") < 0
             && p.effDate.CompareTo("20101212") > 0
             select p;

首先,您不能僅通過將日期轉換為int來比較日期,因為在大多數情況下它將失敗。 使用DateTime ParseParseExact解析字符串並進行比較。

這是因為int.Parse是客戶端調用,Linq提供程序不知道如何將其映射到數據庫函數。

由於字符串采用易於排序的格式,因此可以where p.effDate < "20101212" && p.effDate > "20121212"使用where p.effDate < "20101212" && p.effDate > "20121212"

更好的方法是更改​​數據庫以將日期存儲在date列而不是charvarchar列中。

最后,我找到了一個不錯的答案:

 google = from p in ctx.dates
 where p.effDate.CompareTo(picker1) > 0 && p.effDate.CompareTo(picker2) <0 
select p; 

picker1和picker2都是“ yyyymmdd”中的字符串謝謝大家的幫助

暫無
暫無

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

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