Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you yield return into an IList<T>?

In my service layer for my MVC application I am attempting to convert the linq to sql entity results into my business model entities. I am currently attempting the following code:

    public IList<Project> GetAllProjects()
    {
        var results = from p in _context.Repository<DBMappings.project>()
                      select p;

        foreach (DBMappings.project prj in results.ToList<DBMappings.project>())
            yield return CreateProjectEntityFromDBProject(prj);

    }

Unfortunately, this doesn't seem to work and the only thing I can guess is that yield only works with IEnumerable. Is there any other solution besides creating a new list, adding items in the foreach loop and returning the list? I need to use an IList because methods that use the returned list need to be able to do List Methods such as .Sort().

like image 825
KallDrexx Avatar asked Jan 26 '26 21:01

KallDrexx


1 Answers

if you want to .Sort() you should definitely create a list in your method. using yield saves you some memory - because results are not stored as a single object. This is useful when you just want to walk over results. but if you want to Sort something you need it in memory as a single piece.

like image 121
Andrey Avatar answered Jan 29 '26 12:01

Andrey