-1

want to remove foreach loop and done with Linq....Please suggest

In ViewModal I have LeadStatus Name and in LeadModal i have Id of LeadStatus on basis of Id I have to fatch Name from LeadStatusTable and bind in ViewModal Thanks

List<Entities.LeadViewModel> leadViewModels = new List<Entities.LeadViewModel>();
IEnumerable<Entities.Lead> leads = await _leadRepository.AllNonDeletedAndConvertedLeads();
foreach (var lead in leads)
{

    Entities.ChetuUser chetuUser = await _chetuUserRepository.GetChetuUser(lead.OwnerId);
    if (!string.IsNullOrEmpty(lead.Status))
    {
        LeadStatusMaster leadStatusMaster = await _masterTableRepository.LeadStatusMasterById(lead.Status);
        if (chetuUser != null && leadStatusMaster != null)
        {
            leadViewModels.Add(new Entities.LeadViewModel
            {
                LeadProperty = lead,
                LeadStatusName = leadStatusMaster.Name,
                CreatedDate =  lead.CreatedDate
            });
        }
        else if (chetuUser != null && leadStatusMaster == null)
        {
            leadViewModels.Add(new Entities.LeadViewModel
            {
                LeadProperty = lead,
                LeadStatusName = "",
                CreatedDate = lead.CreatedDate
            });
        }
        else
        {
            leadViewModels.Add(new Entities.LeadViewModel
            {
                LeadProperty = lead,
                LeadStatusName = "",
                CreatedDate = lead.CreatedDate,
                OwnerName = ""
            });
        }
    }
    else
    {
        if (chetuUser != null)
        {
            leadViewModels.Add(new Entities.LeadViewModel
            {
                LeadProperty = lead,
                LeadStatusName = "",
                CreatedDate = lead.CreatedDate,
                OwnerName = chetuUser.EmployeeName
            });
        }
    }
}
return leadViewModels;
Akhilesh
  • 7
  • 3

1 Answers1

2

Your title is different by the asked question. Because you speak about the speed replaceing the foreach with linq will not speed up your loop. The problem is the awaits in it. Moreover the linq's foreach is a little tricky to work with await: C# async await using LINQ ForEach()

Azzy Elvul
  • 1,403
  • 1
  • 12
  • 22