Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to cast after using yield keyword

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading