srinath

srinath

  • 0
  • 144
  • 0

Replace foreach loops to LINQ

Jul 20 2018 7:33 AM
I need to convert 2 for each loops which are shown as below to linq -
 
List<Company> res = new List<Company>();
List<EmployeeCount> result = new List<EmployeeCount>();
 
foreach (string s in empRange)
{
 
List<Company> re = await _entities.Company.Where(a =>                                                 Convert.ToString(a.number_employees_range.ToLower()).
                                                Equals(s.ToLower().ToString())).ToListAsync();
 
res.AddRange(re);
}
 
foreach (Company r in res)
{
 
List<EmployeeCount> empCount = await _entities.EmployeeCount.Where(a =>                                        Convert.ToString(a.Company_ID.ToLower()).
                                       Equals(r.Company_id.ToLower())).
                                       Select((a => new EmployeeCount()
                                       { Company_ID = a.Company_ID,
                                          Industry_ID = a.Industry_ID,                                           Company_Name = a.Company_Name,
                                          City = a.City,                                           
                                          Number_Employees = a.Number_Employees
                                       })).ToListAsync();
 
result.AddRange(empCount);
 
}
 
return result.AsQueryable();
 
 
 
I need to optimize these foreach loops using lambda expressions in order to fetch the data fastly. Please help me on this.

Answers (2)