序列的第一条记录总是在提取?

时间:2013-11-18 07:17:26

标签: c# linq

var trainingclasses = this.trainingClassRepository.GetAllclassSession().Include(x => x.Trainer).Include(x => x.TrainingRoom).Include(x => x.Session).Where(x => x.ClassId == id);
foreach (var tclass in trainingclasses)
{
    double roomcost = trainingclasses.Select(x => x.TrainingRoom.CostPerHour).FirstOrDefault();
    double trainercost = trainingclasses.Select(x => x.Trainer.Cost).FirstOrDefault();
    double duration = trainingclasses.Select(x => x.Session.Duration).FirstOrDefault();
}

在上面的代码中,序列的第一条记录总是在提取。任何人都可以帮助这个。

3 个答案:

答案 0 :(得分:1)

不要在foreach中使用您的集合,而是在遍历列表,因此您可以从tclass获取数据而不是来自trainingClasses。由于您使用了FirstOrDefault

,因此仅提取了第一项

更改为此代码

foreach (var tclass in trainingclasses)
{
    double roomcost = tclass.TrainingRoom.CostPerHour;
    double trainercost = tclass.Trainer.Cost;
    double duration = tclass.Session.Duration;
}

答案 1 :(得分:0)

不清楚,

将您的代码更改为

double roomcost = tclass.TrainingRoom.CostPerHour;

而不是

double roomcost = trainingclasses.Select(x => x.TrainingRoom.CostPerHour).FirstOrDefault();

答案 2 :(得分:0)

调用.ToList()来实现您的收藏

var trainingclasses = this.trainingClassRepository.GetAllclassSession().Include(x => x.Trainer).Include(x => x.TrainingRoom).Include(x => x.Session).Where(x => x.ClassId == id).ToList();