Nick Kahn
Nick Kahn

Reputation: 20078

Replacing foreach loops with LINQ expressions

replacing the foreach loop

IList<EmployeeSearch> empItems = new List<EmployeeSearch>();
EmployeeSearch empItem = new EmployeeSearch();

foreach (var _emp in mediaResults.results)
{
    empItem.Title = _emp.title;
    empItem.Desc = _emp.description;
    empItems.Add(empItem);
}

with the following linq expression and getting error:

empItems = from _emp in employeeResults.results
           select new EmployeeSearch
           {
               Title = _emp.title,
               Desc = _emp.description                                          
           };

Error:

Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IList'. An explicit conversion exists (are you

Upvotes: 0

Views: 570

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 148980

Either add a call to the ToList extension method at the end of your query:

empItems = 
    (from _emp in employeeResults.results
     select new EmployeeSearch
     {
         Title = _emp.title,
         Desc = _emp.description                                          
     })
    .ToList();

Or if you can possibly refactor your code to use an IEnumerable<T> instead, that could possibly be better:

IEnumerable<EmployeeSearch> empItems =
    from _emp in employeeResults.results
    select new EmployeeSearch
    {
        Title = _emp.title,
        Desc = _emp.description                                          
    };

This should generally be used if you're just looping through the results and you don't actually need to add / remove elements from the result set or have per-index access to the results. Converting the query results to a list requires allocation of a single, contiguous array in memory, which is a fairly expensive operation.

Upvotes: 1

David Hoerster
David Hoerster

Reputation: 28701

You need to convert it to a List:

(from _emp in employeeResults.results
                             select new EmployeeSearch
                                 {
                                     Title = _emp.title,
                                     Desc = _emp.description                                          
                                 }).ToList();

Or...change your empItems definitions to use a var implicit typing:

var empItems = from _emp in employeeResults.results
                             select new EmployeeSearch
                                 {
                                     Title = _emp.title,
                                     Desc = _emp.description                                          
                                 };

empItems will be an IEnumerable of EmployeeSearch objects.

Upvotes: 2

Related Questions