我目前正在處理房地產資料,每個串列物體都有一個 ListingDate 和一個 CloseDate。我目前正在嘗試做的是計算給定月份和年份(按年份和月份分組)中有多少串列處于活動狀態。
例如,如果 Listing1 的 ListingDate 為 05/01/2020,CloseDate 為 08/01/2020,那么 5 月、6 月、7 月和 8 月將有 1 個活動計數,一年總共有 4 個。
我正在使用 EF 和 LINQ,并且想知道是否可以以某種方式解決它。
任何幫助或建議表示贊賞。
uj5u.com熱心網友回復:
你當然可以; 如果您將串列映射到它處于活動狀態的每個月,那么您可以簡單地按月對結果進行分組并輕松獲得計數。因此,最棘手的部分是僅得出月份DateTime值,這并不那么棘手。
DateTime從開始和結束日期獲取月份的擴展方法:
public static IEnumerable<DateTime> GetMonths(this DateTime startDate, DateTime endDate)
{
var monthDiff = (endDate.Month - startDate.Month) (12 * (endDate.Year - startDate.Year));
var startMonth = new DateTime(startDate.Year, startDate.Month, 1);
return Enumerable.Range(0, monthDiff 1)
.Select(i => startMonth.AddMonths(i));
}
創建查找:
var listingsByMonth = listings
.SelectMany(l =>
{
return l.ListingDate.GetMonths(l.ClosingDate.AddDays(-1)) // assuming closing date is exclusive
.Select(dt => new KeyValuePair<DateTime, Listing>(dt, l));
})
.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
結果展示:
foreach(var g in listingsByMonth)
{
Console.WriteLine($"{g.Key:yyyy-MM}: {g.Count()}");
}
小提琴
uj5u.com熱心網友回復:
假設日期是在DateTime結構中給出的。(您可以將文本輸入決議為 DateTime,檢查這個)我們可以遍歷包含Listing物體的 List,并執行檢查以查看給定日期是否在 ListingDate 和 ClosingDate 的范圍內。如果檢查成功,則將該物體復制到另一個串列。
DateTime query = ...;
List<Listing> list = ...;
List<Listing> pass = new();
foreach (Listing entity in list)
{
if (entity.ListingTime < query && query < entity.ClosingTime)
pass.Add(entity)
}
在檢查查詢是否在范圍內時,我們可以使用DateTime.Compare()但小于/大于運算子使陳述句更易于閱讀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417522.html
標籤:
