如何編寫Linq/lambda表達式來選擇本週的所有記錄。Linq,Lambda:獲取本週的所有記錄
1周=週日至週六(含)。
例如,如果今天是星期三,我應該得到本週的所有記錄,即從星期天到星期三。
那麼,我沒有寫完代碼,也沒有測試。我正在寫它,只是卡在「thisWeek」。
[HttpPost]
public ActionResult Purchase(PurchaseSearchVM vm)
{
var filter = new PurchaseFilterRepository();
var model = filter.FilterPurchase(vm);
return View(model);
}
public IQueryable<Purchase> FilterPurchase(PurchaseSearchVM vm)
{
var result = db.Purchases.AsQueryable();
if (vm != null)
{
if (!string.IsNullOrEmpty(vm.option))
{
if (vm.option == "today")
{
result = result.Where(p => p.Date.Date == DateTime.Now.Date);
}
else if (vm.option == "yesterday")
{
result = result.Where(p => p.Date.Date == DateTime.Now.Date.AddDays(-1));
}
else if (vm.option == "thisWeek")
{
//help needed here
result = result.Where(p=> p.Date.)
}
else if (vm.option == "thisMonth") { }
else if (vm.option == "lastMonth") { }
else if (vm.option == "thisYear") { }
else if (vm.option == "lastYear") { }
}
if (!string.IsNullOrEmpty(vm.supplier))
{
var value = vm.supplier;
//query here
}
if (vm.fromDate != null || vm.toDate != null)
{
if (vm.fromDate != null && vm.toDate == null)
{
//query here
}
else if (vm.fromDate == null && vm.toDate != null)
{
//query here
}
else if (vm.fromDate != null && vm.toDate != null)
{
//query here
}
}
if (vm.IsPaid != null)
{
//query here
}
}
return result;
}
UI
顯示一些代碼。你試過了什麼? –
[This answer](http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week)顯示了一個可用於擴展的方法獲取本週開始的日期。那麼你的查詢就是'.Where(p => p.Date.Date> = DateTime.Now.StartOfWeek(DayOfWeek.Sunday)&& p.Date.Date <= DateTime.Now.Date);'注意你可以使用' DateTime.Today'而不是'DateTime.Now.Date' –