我有一個2 List<DateTime>
並希望返回不在第二個列表中的第一個列表的子集,但忽略時間。Linq到對象日期時間除了忽略時間
使用Except擴展方法可以做到這一點嗎?
var missingDates = dateList1.Except(dateList2);
我會需要兩個列表中的時間設置爲00:00:00
或者是有一些方法可以讓我用.Date
屬性來比較?
我有一個2 List<DateTime>
並希望返回不在第二個列表中的第一個列表的子集,但忽略時間。Linq到對象日期時間除了忽略時間
使用Except擴展方法可以做到這一點嗎?
var missingDates = dateList1.Except(dateList2);
我會需要兩個列表中的時間設置爲00:00:00
或者是有一些方法可以讓我用.Date
屬性來比較?
試試這個:
var missingDates = dateList1.Select(x=>x.Date).Except(dateList2.Select(y=>y.Date));
雖然這完全忽略了時間,這意味着在你的結果的時候會丟失,也...
在第二個想法:你當然可以實現自定義IEqualityComparer
保存時間結果:
public class DateComparer : IEqualityComparer<DateTime>
{
public bool Equals(DateTime left, DateTime right)
{
return left.Date.Equals(right.Date);
}
public int GetHashCode(DateTime dateTime)
{
return dateTime.Date.GetHashCode();
}
}
,然後使用該比較器:
var missingDates = dateList1.Except(dateList2, new DateComparer());
這會忽略在比較的時間,但隨着時代的完整返回的日期:
List<DateTime> missingDates = dateList1.Where(list1Item => !dateList2.Exists(list2Item => list2Item.Date == list1Item.Date)).ToList();
用'Any'替換'Exists',然後這也是一個有效的答案。 – Spontifixus
@Spontifixus:這裏存在什麼問題?它和Any一樣。 – Carl
你是對的Carl - 我的錯誤是我在兩個陣列上嘗試了LINQPad。 '存在(謂詞
奏效了...謝謝! – woggles
查看我修改的答案,關於如何在必要時保留結果中的時間... – Spontifixus