【发布时间】:2018-02-25 23:49:03
【问题描述】:
我正在使用 Left-Join 和 groupBy 进行 LINQ 查询,所以我有可能有也可能没有答案集合的问题列表。我想要按问题分组的所有问题及其答案列表,如果为空则不想添加。
我当前的解决方案工作正常,但它仍然添加一个带有 null 的列表,其中没有答案,因此在 Answer count() 上给了我错误的结果
var dhd = (from question in Context.Questions
join answer in Context.Answers on question.Id equals answer.QuestionId into ps
from answerDetail in ps.DefaultIfEmpty()
group answerDetail by question into grouped
select new
{
Question = grouped.Key,
Answer = grouped.ToList(),
//Answer = grouped.ToList() == null ? "(No Answer)" : grouped.Select(x => x.Value).FirstOrDefault(),
TotalAnswerCount = grouped.Count()
}).ToList();
我在上面的代码中尝试了以下脚本,它抛出空异常
Answer = grouped.ToList() == null ? "(No Answer)" : grouped.Select(x => x.Value).FirstOrDefault(),
【问题讨论】:
标签: linq