我有一个性能问题,我正在调用一个项目列表,然后使用 foreach 循环将每条记录与同一张表中的其他记录进行比较。有没有办法通过一次调用数据库来做到这一点?现在,与大表相比,此查询运行速度非常慢。
我正在使用实体框架 5。
这是一个例子:
var animals = new List<Animal>
{
new Animal
{
Id = 1,
Name = "Tiger",
Birthday = new DateTime(2012, 01, 01, 9, 0, 0)
},
new Animal
{
Id = 2,
Name = "Tiger",
Birthday = new DateTime(2012, 01, 01, 20, 0, 0)
},
new Animal
{
Id = 3,
Name = "Lion",
Birthday = new DateTime(2012, 01, 01, 7, 0, 0)
},
new Animal
{
Id = 4,
Name = "Lion",
Birthday = new DateTime(2012, 01, 01, 14, 0, 0)
},
};
var animalsToCompareTo = animals.Where (a => a.Id == 2 || a.Id = 4);
foreach (var animalToCompareTo in animalsToCompareTo)
{
bool isTheSecondTigerOfTheDay = animals.Any (a => a.Name == animalToCompareTo.Name &&
a.Birthday.Day == animalToCompareTo.Birthday.Day &&
a.Birthday.Month == animalToCompareTo.Birthday.Month &&
a.Birthday.Year == animalToCompareTo.Birthday.Year &&
a.Birthday < animalToCompareTo.Birthday
);
if (isTheSecondTigerOfTheDay)
{
//do something
}
}