简体   繁体   中英

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

How can I combine these two lists in one List?

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);
    }

Use a ViewModel to store two list and pass it to the View

The problem you are facing is a common one. As already mentioned by @Arripe here, you can create a ViewModel that is a composite class with the properties from each class that you want to use in your presentation layer. With a simple search for "create viewmodel asp.net mvc" or similar, you can find a guide to creating a ViewModel. Yours might be called "QuestionAnswerViewModel".

Constructing the actual ViewModel can be clunky (loop through each collection, mapping properties as you go), or you can be more creative with it.

For example, you could try joining the two query results into a combined result list, with the results being of type.

See @JonSkeet example here: how do I join two lists using linq or lambda expressions

I think what you're trying to get is Questions with number of Answers you have for them, right? If that's the case, then I think this should be the simplest solution. Of course you'll need to update the View to work with the new object.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM