[英]How to simplify filtered iqueryable date linq expression?
我嘗試從數據庫過濾變量IQueryable<MyType> itemsFiltered
中的日期:
itemsFiltered = itemsFiltered.Where(i => i.Dataout.Value.ToString("dd.MM.yyyy").Contains(date));
但我收到錯誤The LINQ expression could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
The LINQ expression could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
我可以像這樣重寫表達式:
itemsFiltered = itemsFiltered.Where(i => (
(
i.Dataout.Value.Day.ToString().Length > 1 ?
i.Dataout.Value.Day.ToString() :
"0" + i.Dataout.Value.Day.ToString()
) + "." + (
i.Dataout.Value.Month.ToString().Length > 1 ?
i.Dataout.Value.Month.ToString() :
"0" + i.Dataout.Value.Month.ToString()
) + "." +
i.Dataout.Value.Year.ToString()).Contains(date));
它有效,但看起來很糟糕。 如何簡化這個?
添加
問題是:當用戶輸入 11 時,不知道是日、月(11 月)還是年(2011 年)。 date
是string
,可以是"11"
或"11.11"
或"01.01"
或"11.01.201"
等。
對於 LINQ 到 EF Core,您可以使用默認字符串轉換轉換DateTime
的Date
屬性:
itemsFiltered = itemsFiltered.Where(i => i.Dataout.Value.Date.ToString().Contains(date));
如果您需要特定格式以便搜索匹配顯示以方便用戶(例如,他們可能會搜索"11.07"
,然后在標准轉換中使用Substring
(我不確定默認值是否與您的語言環境匹配):
itemsFiltered = itemsFiltered.Select(i => new { i, sd = i.Dataout.Value.Date.ToString() }).Where(isd => (isd.sd.Substring(8,2) + "." + isd.sd.Substring(5,2) + "." + isd.sd.Substring(0,4)).Contains(date));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.