Search code examples
c#linqasp.net-core.net-coreasp.net-core-mvc

Convert foreach to select statement


I have below code written in foreach loop, I want to convert it to linq select method.

I tried following, but it's not working. So any idea on this


Solution

  • var bidsData = bidderDatas.Select( bd => new BidderDataDTO() {
            TenderId = bd.TenderId,
                             // I think you may want  "bd.TenderId" here  ˇ
            ClosingDate = _context.Tenders.FirstOrDefault(x => x.Id == tenderid)?.ClosingDate,
            CompanyName = _context.Companies.FirstOrDefault(x => x.Id == x.CompanyId)?.CompanyName,
            FullName = _context.Users.FirstOrDefault(x => x.userid == bd.CreatedUser)?.Select(x => $"{x.Firstname} {x.Lastname}")
            Price = bd.Price,
            Email = _context.Users.FirstOrDefault(x => x.Userid == x.CreatedUser)?.Email
       });
    

    Note this creates an IEnumerable instead of a List, but that's often better, and if you really need a List you can call .ToList() to get it.

    We could probably improve performance a little more by extending the lambda to avoid needing to call FirstOrDefault() on the same Users collection more than once. But if I really cared about performance I'd write raw SQL. I tend to reserve linq queries for in-memory collection types or only the simplest table => object mappings.