在一个 LINQ 查询中获取总计数和筛选结果?

Get Total Count and Filter Results in one LINQ query?

我有一个查询,该查询正在获取基于联接的对象列表(与此问题无关)并根据创建日期是否在过去 60 天内进行过滤。这是工作。我想做的是:

  1. 知道在没有 createdDate where 子句的查询中有多少对象,加上 return ResultObj 带有 createdDate where 子句的列表。 return 对象在我看来更像这样:
public class QueryResult 
{
    public long TotalPossibleCount {get; set;}
    public List<ResultObj> Results {get; set;}
}
IQueryable<ResultObj> res = 
    from tA in ctx.TableA
    join tB in ctx.TableB on tA.Id equals tb.CustId
    where tA.Id == 12345 && 
        tB.CreatedDate >= DateTime.Now.AddDays(-60)
    select new ResultObj
    {
        // some object properties
    };

return await res.OrderByDescending(x => x.CreatedDate).ToListAsync();

这可以在一次查询中完成吗?如果我没有 tb.CreatedDate >= ...加上数据对象列表,请获取所有可能的计数?

您可以使用以下查询并往返数据库一次来完成此操作:

var taFiltered = ctx.TableA.Where(x => x.Id == 12345);

var joined = 
    from tA in taFiltered
    join tB in ctx.TableB on tA.Id equals tb.CustId
    select new { tA, Tb };
    
var res = 
    from tA in taFiltered
    select new QueryResult
    {
        TotalPossibleCount = joined.Count(),
        Results = ctx.TableB
            .Where(tB => tA.Id == tB.CustId 
                tB.CreatedDate >= DateTime.Now.AddDays(-60)
            .OrderByDescending(x => x.CreatedDate)
            .Select(x => new ResultObj
            {
                 // some object properties
            }
            .ToList()
    };

return await res.FirstOrDefautAsync();