我有一个大型数据库,我需要使用 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();
每个客户都有一些其他属性,例如 Id
、PhoneNumber
、Address
和...。要从我的表中访问 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/