在LINQ中将DateTime与毫秒进行比较



我正在构建一个windows服务,该服务每5分钟从SQL数据库获取数据并将其存储在.txt文件中。我想做的是,当我的服务每5分钟检查一次数据库时,它应该检查txt文件上的最后一条日期时间记录,并在数据库中找到它。如果它找到相同的日期时间,它应该获取该日期时间之后的所有较新记录。我正在努力做到尽可能精确,不会错过记录,所以我认为比较每个日期的毫秒数是个好主意。这就是我目前所掌握的,但我知道类型为Datetime的x.Datetime不会获取毫秒和日期"lastDate";是我从添加了毫秒的txt文件中获取的日期。

dbData = db.Table.Where(x => x.Datetime < lastDate).ToList();

此外,数据库上的列具有与日期时间一起存储的毫秒数。

因此,表中的行具有Datetime属性。您只想提取以前未提取的行,并且不想错过任何行。

问题是,一旦查询返回,可能已经添加了新行。因此,在您以毫秒X处理提取的数据之前,可能已经添加了新的数据

最好记住最后添加的行的DateTime:

private DateTime lastFetchedDate = ... 

每隔几分钟调用以下过程:

private void FetchAndProcessNewData()
{
var dbData = db.Table.Where(row => row.Datetime > lastFetchedDate)
.OrderByDescenting(row => row.DateTime)
.ToList();
if (dbData.Any())
{
ProcessFetchedData(dbData);
lastFetchedDate = dbData[0].DateTime;
}
// else: no new rows; nothing to process, no new lastFetchedDate needed
}

订购所有的行有点浪费。一个小的优化是不排序列表,而是计算最大DateTime。这样你只需要枚举一次提取的数据

lastFetchedDate = dbData.Select(row => row.DateTime).Max();

DateTimes没有Max,但扩展方法很容易创建。如果您不熟悉扩展方法,请参阅扩展方法解密

public static DateTime Max(this IEnumerable<DateTime> source)
{
// TODO: exception if source == null
var enumerator = source.GetEnumerator();
// initialize the first DateTime as the largest:
if (enumerator.MoveNext()
{
var max = enumerator.Current;
// enumerate the rest:
while (enumerator.MoveNext())
{
if (enumerator.Current > max)
max = enumerator.Current;
}
return max;
}
// else: empty source. Decide what to do: exception? return DateTime.MinValue;
}

用法:

var dbData = db.Table.Where(row => row.Datetime > lastFetchedDate).ToList();
if (dbData.Any())
{
ProcessDbData(dbData);
this.lastFetchedData = dbData.Select(row => row.DateTime).Max();
}

最新更新