-3

我有一种方法,它使用实体框架为服务点应用程序查询 SQL Server CE 数据库并打印结果。我使用的代码有效,但是当数据库大小增加时,该方法需要更长的时间来执行。我认为这是因为数据库被多次查询以达到预期的结果。我真正想做的是查询数据库一次并将结果存储在内存中,然后针对存储在内存中的数据运行所有其他查询。

该方法主要需要查询数据库以查找今天的交易(ZTotaled == null),然后打印交易日每30分钟的交易数量和总销售额。

我正在使用的代码看起来像这样......

var ztotal = from z in context.Transactions
where z.ZTotaled == null
select new { z.NumerPeople, z.PricePaid, z.ZTotaled, z.DateTime }; 


var ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 18 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };


totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);


sb2.Append(string.Format("{0}{1,10}{2,16}", "18.00 - 18.30", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);

ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 18 && z.DateTime.Minute >= 30
select new { z.NumerPeople, z.PricePaid };

totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);

sb2.Append(string.Format("{0}{1,10}{2,16}", "18.30 - 19.00", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);

ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 19 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };

totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);

sb2.Append(string.Format("{0}{1,10}{2,16}", "19.00 - 19.30", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);

ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 19 && z.DateTime.Minute >= 30
select new { z.NumerPeople, z.PricePaid };

totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);

sb2.Append(string.Format("{0}{1,10}{2,16}", "19.30 - 20.00", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);

ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 20 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };

totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);

sb2.Append(string.Format("{0}{1,10}{2,16}", "20.00 - 20.30", totalPeople.ToString(), totalPaid.ToString()) + Environment.NewLine);

有人可以指点我使这段代码更有效率的方向吗?

非常感谢

詹姆士

4

1 回答 1

0

我认为我遇到的性能问题是由于延迟执行造成的。通过将 .ToList() 添加到第一个 LINQ 查询,它被迫立即将查询执行到对象列表中。然后针对内存中的该列表执行所有进一步的查询。

var ztotal = (from z in context.Transactions
where z.ZTotaled == null
select new { z.NumerPeople, z.PricePaid, z.ZTotaled, z.DateTime }).ToList(); 


var ztotal2 = from z in ztotal
where z.ZTotaled == null && z.DateTime.Hour == 18 && z.DateTime.Minute < 30
select new { z.NumerPeople, z.PricePaid };


totalPeople = ztotal2.Sum(o => o.NumerPeople);
totalPaid = ztotal2.Sum(o => o.PricePaid);


sb2.Append(string.Format("{0}{1,10}{2,16}", "18.00 - 18.30", totalPeople.ToString(),      totalPaid.ToString()) + Environment.NewLine);
于 2013-08-20T09:50:52.600 回答