Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert foreach to select statement

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

List<BidderDataDTO> bidsData = new List<BidderDataDTO>();

if(bidderDatas.Count > 0)
{
    foreach (var bidderData in bidderDatas)
    {
        var data = new BidderDataDTO();

        data.TenderId = bidderData.TenderId;
        data.ClosingDate = _context.Tenders.Where(x => x.Id == tenderid).Select(x => x.ClosingDate).FirstOrDefault();
        data.FullName = _context.Users.Where(x => x.Userid == bidderData.CreatedUser).Select(x => x.Firstname + " " + x.Lastname).FirstOrDefault();
        data.Price = bidderData.Price;

        bidsData.Add(data);
    }
}

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

 bidderDatas.Select(x => new BidderDataDTO()
 {
     TenderId = x.TenderId,
     ClosingDate = _context.Tenders.Where(x => x.Id == tenderid).Select(x => x.ClosingDate).FirstOrDefault(),
     CompanyName = _context.Companies.Where(x => x.Id == x.CompanyId).Select(x => x.CompanyName).FirstOrDefault(),
     FullName = _context.Users.Where(x => x.Userid == x.CreatedUser).Select(x => x.Firstname + " " + x.Lastname).FirstOrDefault(),
     Price = x.Price,
     Email = _context.Users.Where(x => x.Userid == x.CreatedUser).Select(x => x.Email).FirstOrDefault(),
 }).ToList();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading