如何将日期与时间字符串拼接后和DateTime比较?SQL转LINQ实现
SQL转LINQ实现日期时间拼接比较并统计行数
实现思路
将字符串类型的DateCreate和TimeCreate拼接后转换为DateTime类型,与指定目标时间比较,同时过滤TypeForm=15和NameButton=2的记录,最后统计符合条件的行数并判断是否大于0。
代码实现
1. LINQ to Objects(内存集合场景)
适用于数据已加载到内存中的情况:
// 定义目标时间 var targetDateTime = DateTime.Parse("2022/11/06 02:49:51"); // 统计符合条件的行数 int matchingCount = viewAllTranUserList .Where(item => item.TypeForm == 15 && item.NameButton == 2 && DateTime.Parse($"{item.DateCreate} {item.TimeCreate}") <= targetDateTime) .Count(); // 判断结果是否大于0 bool hasMatchingData = matchingCount > 0;
注意:如果数据中存在格式不合法的日期/时间字符串,建议使用DateTime.TryParse做安全转换,避免抛出异常。
2. LINQ to Entities(EF/EF Core等ORM场景)
针对数据库查询场景,需确保表达式能被EF翻译为对应的SQL语句:
EF Core版本:
var targetDateTime = DateTime.Parse("2022/11/06 02:49:51"); int matchingCount = dbContext.ViewAllTranUser .Where(item => item.TypeForm == 15 && item.NameButton == 2 && EF.Functions.ParseDateTime($"{item.DateCreate} {item.TimeCreate}") <= targetDateTime) .Count(); bool hasMatchingData = matchingCount > 0;
EF6版本:
var targetDateTime = DateTime.Parse("2022/11/06 02:49:51"); int matchingCount = dbContext.ViewAllTranUser .Where(item => item.TypeForm == 15 && item.NameButton == 2 && DbFunctions.CreateDateTime( DateTime.Parse(item.DateCreate).Year, DateTime.Parse(item.DateCreate).Month, DateTime.Parse(item.DateCreate).Day, DateTime.Parse(item.TimeCreate).Hour, DateTime.Parse(item.TimeCreate).Minute, DateTime.Parse(item.TimeCreate).Second) <= targetDateTime) .Count(); bool hasMatchingData = matchingCount > 0;
内容的提问来源于stack exchange,提问作者Mohamed Fouad
相关产品推荐
相关产品推荐

