.NET Core C#:能否通过逻辑拆分LINQ查询操作符?
逐步构建LINQ查询:叠加操作符示例
下面是一组逐步扩展的LINQ查询,每个查询都包含前一个查询的所有操作符,并在调用链中新增一个操作符,清晰展示查询的构建过程:
基础查询:仅日期过滤
这是最基础的查询,仅通过Where筛选出近31天的记录:Foo = await (_context.Foo.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31)).ToListAsync();新增:记录ID过滤
在基础查询的基础上,新增第二个Where条件,筛选出指定recordid的记录:Foo = await (_context.Foo.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31) .Where(f => f.recordid == x)).ToListAsync();新增:按日期排序
叠加OrderByDescending,将结果按date1倒序排列:Foo = await (_context.Foo.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31) .Where(f => f.recordid == x) .OrderByDescending(f => f.date1)).ToListAsync();新增:选择指定字段
使用Select投影,只获取需要的字段(示例中选择id、date1和recordid):Foo = await (_context.Foo.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31) .Where(f => f.recordid == x) .OrderByDescending(f => f.date1) .Select(f => new { f.id, f.date1, f.recordid })).ToListAsync();新增:跳过前N条记录
加入Skip操作,跳过前5条记录(可根据需求调整数值):Foo = await (_context.Foo.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31) .Where(f => f.recordid == x) .OrderByDescending(f => f.date1) .Select(f => new { f.id, f.date1, f.recordid }) .Skip(5)).ToListAsync();新增:限制返回数量
最后叠加Take,只返回后续的10条记录:Foo = await (_context.Foo.Where(f => (Convert.ToDateTime(f.date1) - today).TotalDays < 31) .Where(f => f.recordid == x) .OrderByDescending(f => f.date1) .Select(f => new { f.id, f.date1, f.recordid }) .Skip(5) .Take(10)).ToListAsync();
另外提个小建议:如果date1在数据库中已经是DateTime类型,尽量避免在LINQ查询中使用Convert.ToDateTime,直接比较日期会让EF Core生成更高效的SQL语句哦~
内容的提问来源于stack exchange,提问作者ogg130
相关产品推荐
相关产品推荐

