如何在 mvc c# 中组合两个查询并获得一个列表

How to combine two queries and get one List in mvc c#

如何将这两个列表合并为一个列表?

public IActionResult Open(int? id)
    {
        
        var questions = (from q in _context.Questions where q.CategoryId == id select q).ToList();

        var answers = (from s in _context.Answers
                       join b in questions
                       on s.QId equals b.ID
                       group s by b.ID into g
                       select g.Count()).ToList();
        
        if (questions == null)
        {
            return NotFound();
        }
        
        return View(questions);
    }

使用 ViewModel 存储两个列表并将其传递给 View

您遇到的问题很常见。正如@Arripe 在这里已经提到的,您可以创建一个 ViewModel,它是一个复合 class,其中包含您要在表示层中使用的每个 class 的属性。通过简单搜索“create viewmodel asp.net mvc”或类似内容,您可以找到创建 ViewModel 的指南。您的可能称为“QuestionAnswerViewModel”。

构建实际的 ViewModel 可能很笨拙(遍历每个集合,边走边映射属性),或者您可以更有创意。

例如,您可以尝试将两个查询结果加入一个组合结果列表,结果类型为 .

在此处查看@JonSkeet 示例:how do I join two lists using linq or lambda expressions

我想你想得到的是问题和你对他们的答案数量,对吧?如果是这样,那么我认为这应该是最简单的解决方案。当然,您需要更新视图才能使用新对象。

var questionsWithAnswerCount = _context.Questions.Where(q => q.CategoryId == id)
                                                 .GroupJoin(_context.Answers, // list you join with
                                                               q => q.ID, // "main" list key
                                                               a => a.QId, // joined list key
                                                               (q, a) => new { Question = q, AnswerCount = a.Count() } // what to do with result - create new object that has Questions & Number of answers
                                                            )
                                                 .ToList();

if (questionsWithAnswerCount.Any()) // No need to check for null since you're calling .ToList() which will return an empty list, even when no elements were found, instead call .Any() to check if the list is empty or not
{
    return View(questionsWithAnswerCount);
}

return NotFound();