Something like this would work
var results = from x in context.Tests
group x by new { x.DeptId, x.StudentId, x.TeacherId } into grp
select new
{
grp.Key.DeptId,
grp.Key.StudentId,
grp.Key.TeacherId,
A = grp.FirstOrDefault(x => x.TestName == "A")?.TestValue,
B = grp.FirstOrDefault(x => x.TestName == "B")?.TestValue
};
This requires C# 6 for the null-conditional operator ?.
, but you could do this instead
A = grp.Where(x => x.TestName == "A").Select(x => x.TestValue).FirstOrDefault();
You might also want to filter out other tests with a where
after the from
to avoid results were both A and B would end up being null
, like this
where x.TestName == "A" || x.TestName == "B"
Of course you could still end up with null values for A and B if the DeptId-StudentId-TeacherId combination only has one of those tests in your DB.
2
solved Generating list in a following format [closed]