本文介绍了将具有lambda表达式的2个foreach循环转换为一个或两个lambda语句,以便为每个循环删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我需要为每个循环转换2,如下所示为linq -



Hi,

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 indType)
          {
              List<Company> re = _entities.Company.Where(a => Convert.ToString(a.industry_id.ToLower()).Equals(s.ToLower().ToString())).ToList();
              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();







我需要使用lambda表达式优化这些foreach循环以获取数据快速。请帮帮我。



我尝试过:



尝试如下 -



res.ForEach(i => i.company_id).intersect(_entities.EmployeeCount.Select(i => i.company_id)。 ToList();



显示它只返回List< string>,我需要List< employeecount>。无法选择EmployeeCount实体的值。




I need to optimize these foreach loops using lambda expressions in order to fetch the data fastly. Please help me on this.

What I have tried:

tried like below -

res.ForEach(i => i.company_id).intersect(_entities.EmployeeCount.Select(i => i.company_id).ToList();

its showing it returns List<string> only, I need List<employeecount>. Unable to select the values of EmployeeCount entity.

推荐答案

return _entities.EmployeeCount.Where(ec => indType.Contains(ec.Industry_ID));



如果 EmployeeCount Industry_ID 列c>实体与 Company 实体上的同名列不匹配,那么您需要一个导航属性:


If the Industry_ID column on the EmployeeCount entity doesn't match the column of the same name on the Company entity, then you'll need a navigation property:

return _entities.EmployeeCount.Where(ec => indType.Contains(ec.Company.Industry_ID));



如果 EmployeeCount 集合未返回 EmployeeCount的实例 class,然后添加 .Select(...)到最后:


If the EmployeeCount set doesn't return an instance of your EmployeeCount class, then add a .Select(...) to the end:

return _entities.EmployeeCount
    .Where(ec => indType.Contains(ec.Industry_ID))
    .Select(ec => new EmployeeCount
    {
        Company_ID = ec.Company_ID, 
        Industry_ID = ec.Industry_ID, 
        Company_Name = ec.Company_Name, 
        City = ec.City, 
        Number_Employees = ec.Number_Employees,
    });


List<EmployeeCount> result = new List<EmployeeCount>();

foreach (EmployeeCount c in _entities.EmployeeCount)
{
    if (indType.Contains(c.industry_id))
    {
        result.Add(c);
    }
}

return result;


这篇关于将具有lambda表达式的2个foreach循环转换为一个或两个lambda语句,以便为每个循环删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 15:48