【问题标题】:How to combine two queries and get one List in mvc c#如何在mvc c#中组合两个查询并获取一个列表
【发布时间】:2021-11-21 18:28:59
【问题描述】:

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

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

【问题讨论】:

  • 列表不能有两种不同类型的项目。
  • @viveknuna 父类的不同子类是否计算在内?
  • 如何将这两个列表合并到一个列表中? - 为什么要这样做?
  • @CaiusJard 我的意思是这里的问题和答案看起来完全不相关的类。但我明白你的意思,你有鹰眼先生:尊重????
  • 我的意思是执行一个查询并得到一个列表

标签: c# model-view-controller


【解决方案1】:

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

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

例如,您可以尝试将两个查询结果连接到一个组合结果列表中,结果的类型为 。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-01
        • 2015-06-25
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        • 2018-08-14
        • 2020-10-12
        • 2021-10-20
        相关资源
        最近更新 更多