如果我比较两个文件而不对这些查询进行舍入分钟结果
var queryList1Only3 = (from file in list1 select file).Except(list2, myFileCompare2);
var queryList1Only33 = (from file in list2 select file).Except(list1, myFileCompare2);
是
12/14/2010 4:14:10 PM C:\xml\Tracker.xml
10/13/2010 3:00:27 PM D:\xml\Tracker.xml
但是如果我将日期时间缩短到分钟,则查询列表的结果为
12/14/2010 4:14:10 PM C:\xml\Tracker.xml
并且第二个查询只返回空,因为我只修改了C:\xml\Tracker.xml
文件而另一个文件没有更改......
和
public class FileCompareLastwritetime : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
{
public FileCompareLastwritetime() { }
public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
{
return RoundToMinute(f1.LastWriteTime) == RoundToMinute(f2.LastWriteTime);
}
public int GetHashCode(System.IO.FileInfo fi)
{
return RoundToMinute(fi.LastWriteTime).GetHashCode();
}
}
public static DateTime RoundToMinute(DateTime time)
{
return new DateTime(time.Year, time.Month, time.Day,
time.Hour, time.Minute, 0, time.Kind);
}
有什么建议吗?
编辑:
IEnumerable<System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
答案 0 :(得分:1)
DateTime equals比较Ticks,使用time.Year,time.Month等设置值时可能略有不同。我找到的最佳DateTime截断方法如下:
///<summary>
/// Extension methods for DateTime class
///</summary>
public static class DateTimeExt
{
/// <summary>
/// <para>Truncates a DateTime to a specified resolution.</para>
/// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
/// </summary>
/// <param name="date">The DateTime object to truncate</param>
/// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
/// <returns>Truncated DateTime</returns>
public static System.DateTime Truncate(this System.DateTime date, long resolution)
{
return new System.DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
}
}
用法:myDateTime.Truncate(TimeSpan.TicksPerMinute)截断为分钟。它没有圆,但你的例子也没有。