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

时间:2014-04-13 12:20:57

标签: 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...
            }

但这很慢! 我希望Id中的每个项目都有statisticList来快速查找我的数据库中的记录。这可能吗?

或者有没有办法在statisticList中拥有所有这些属性?像列表中的子列表一样?

2 个答案:

答案 0 :(得分:3)

我在Linq-> Sql或EntityFramework中为零。我将根据Linq->对象提供一些想法,你可以尝试在Linq-&gt; Sql中转换它。

首先where 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,如果它没有帮助,请道歉。我会删除我的答案。

答案 1 :(得分:0)

我找到了答案。我建了一堂课:

public class StatisticsGroup
    {
        public IEnumerable<DB.TBStatistic> TBStatisticRecords { get; set; }
        public string Customer { get; set; }
        public int Count { get; set; }
    }

然后我在我的查询中使用了这个类:

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 StatisticsGroup
                                 {
                                     Customer = grp.Key,
                                     Count = grp.Count(),
                                     TBStatisticRecords = grp.Select(p=> p)
                                 }).ToList();

现在我已经了解了TBStatisticRecords

中的所有细节