我正在使用Left-Join和groupBy进行LINQ查询,所以我有可能有也可能没有答案集合的问题列表。我想要所有的问题分组的问题和他们的答案列表,如果它是空的,那么就不想添加。
我当前的解决方案运行良好,但它仍然添加了一个空列表,其中没有答案,因此在答案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(),发布于 2018-02-25 19:04:58
当你调用ps.DefaultIfEmpty()时,它会为不匹配的元素创建一个null的列表。如果您只想获取null,而不是一个包含null元素的列表,那么可以尝试以下代码:
Answer = grouped.FirstOrDefault() == null ? null : grouped.ToList(),如果没有匹配,则答案为空,否则将得到一个列表。
发布于 2018-02-25 17:40:15
我认为问题是因为类型而发生的,所以试试这个:
Answer = grouped.ToList() == null ? null : grouped.Select(x => x.Value).FirstOrDefault(),https://stackoverflow.com/questions/48972031
复制相似问题