c# - 访问 groupby 中每个项目的详细信息

标签 c# database linq group-by

我有一个大型数据库,我需要使用 groupby 来查找每个 Customer 的计数。这是我的查询:

var statisticList = (from item in Connection.DBConnection.TBStatistics
                                 where item.Date >= startDate && item.Date <= endDate
                                 group item by item.Customer into grp
                                 where grp.Count() > 1
                                 select new
                                 {
                                     Customer = grp.Key,
                                     Count = grp.Count(),
                                 }).ToList();

每个客户都有一些其他属性,例如 IdPhoneNumberAddress 和...。要从我的表中访问 statisticList 中每个项目的详细信息:

foreach (var Cus in statisticList)
            {
                var allPlateDetail = (from item in Connection.DBConnection.TBStatistics
                                      where item.Customer == Cus.Customer &&
                                      item.Date >= startDate && item.Date <= endDate
                                      select item).ToList();

                //More Code...
            }

但是速度很慢! 我想要 statisticList 中每个项目的 Id 以快速找到我数据库中的记录。这可能吗?

或者有什么方法可以在 statisticList 中拥有所有这些属性?像一个子列表进入列表?

最佳答案

我在 Linq->Sql 或 EntityFramework 中是零。我将根据 Linq->Objects 提供一些想法,您可以尝试在 Linq->Sql 中转换它。

首先,其中 grp.Count() > 1 的复杂度为 O(n),因此我们使用 grp.Any(),这是 O(1) 操作。然后我们可以像这样获取通过 GroupBy 获取的组。

var statisticList = (from item in Connection.DBConnection.TBStatistics       
          where item.Date >= startDate && item.Date <= endDate
                     group item by item.Customer into grp
                     where grp.Any()
                     select new
                     {
                         Customer = grp.Key,
                         //Count = grp.Count(), Note I think we don't need it we can use GroupItems.Count instead
                         GroupItems = grp.ToList()
                     }).ToList();

foreach (var Cus in statisticList)
{
    //Do whatever with Cus.GroupItems
}

我不确定这是否适用于 Linq->Sql 或 EntityFramework,如果没有帮助,我们深表歉意。我会删除我的答案。

关于c# - 访问 groupby 中每个项目的详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23042672/

相关文章:

c# - 在异步操作的任务中在哪里处理异常?

c# - 从映射驱动器或共享文件夹运行 .NET 程序

MongoDB 修复命令失败

c# - 哪个是最高效的 DataSet 查询操作?

linq - 如何将 linq 结果作为字符串数组?

C# Timespan 毫秒与 TotalMilliseconds

c# - 为什么我的表格这么害羞?

sql - 根据特定要求限制来自 SQL 的记录数

mysql - 如何查找另一个表中不存在的内容?

c# - 将字符串转换为 Linq lambda 表达式