Home > OS >  How to cast after using yield keyword
How to cast after using yield keyword

Time:12-28

I want to use the Yield keyword in a return statement but after using it I have a problem of cast :

Cannot implicitly convert type 'IEnumerable - Mderator' to 'Moderator'. An explicit conversion exists (are you missing a cast?)

When I delete the Yield keyword , I don't have the error , and I don't want using dynamic as type return.

This is my Method :

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

CodePudding user response:

You are misinterpreting the use of yield return. yield return is used to generate an IEnumerable from multiple successive returns of a basic type.

For instance:

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

will generate an IEnumerable.

Here you already have an enumeration so you don't need yield at all.

CodePudding user response:

you don' t need yield in this case. Try this

 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();
  }
  • Related