【问题标题】:How to cast after using yield keyword使用 yield 关键字后如何转换
【发布时间】:2021-12-27 17:24:16
【问题描述】:

我想在 return 语句中使用 Yield 关键字,但使用后我遇到了强制转换问题:

无法将类型“IEnumerable - Mderator”隐式转换为 “主持人”。存在显式转换(您是 缺少演员表?)

当我删除 Yield 关键字时,我没有错误,我不想使用 dynamic 作为类型返回。

这是我的方法:

        public IEnumerable<Moderator> GetAllModerators(int id)
    {
        RtcRepository repoRtc = new RtcRepository(db);
        yield return repoRtc.GetByID(id).Collection1.SelectMany(x => x.Collection2.Select(y => y.Moderator));
    }

【问题讨论】:

  • “我想在 return 语句中使用 Yield 关键字” - 实际上,你没有。无论如何,不​​是因为你所展示的。当你删除它时,如果你没有收到错误,那是什么问题?
  • @madreflection 我不想删除它,但是当我删除它时我说它有效,我没有错误,添加后我遇到了演员表的问题
  • 再一次,你不想要它。 yield return 只能产生一个元素。要对整个集合执行yield return,您需要迭代集合,例如使用foreach 循环。

标签: c# entity-framework linq


【解决方案1】:

您误解了收益回报的使用。 yield return 用于从一个基本类型的多个连续返回中生成一个 IEnumerable。

例如:

for (int i = 0; i < 100; i++)
   yield return i;

将生成一个 IEnumerable。

这里你已经有一个枚举,所以你根本不需要 yield。

【讨论】:

    【解决方案2】:

    在这种情况下您不需要 yield。试试这个

     public IEnumerable<Moderator> GetAllModerators(int id)
     {
            RtcRepository repoRtc = new RtcRepository(db);
          return repoRtc.GetByID(id).Collection1
         .SelectMany(x => x.Collection2.Select(y => y.Moderator)).FirstOrDefault();
      }
    

    【讨论】:

    • FirstOrDefault 是从哪里来的?
    • @LasseV.Karlsen 查询在另一个点亮的内部有选择列表。有时它会以列表列表的形式返回结果。在这种情况下,它很有用。
    猜你喜欢
    • 2011-12-25
    • 2020-11-28
    • 2022-01-10
    • 2011-06-08
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2014-09-27
    • 2020-10-02
    相关资源
    最近更新 更多