0

I built a code that seems a bit cumbersome to me and I believe it can be optimized in linq

I have a table of all the users who liked the article- At first I did a search of all the likes of the article, I then made a loop that checks the user id and added it to a new list.


Users cUser = new Users ();
List <Users> allUsers = new List <Users> ();
List <Likes> allLikes = await _context.Likes.Where (x => x.AfazaId == id) .ToListAsync ();
foreach (Likes item in allLikes)
{
    cUser = await _context.User.Where (x => x.Id == item.Id).FirstOrDefaultAsync ();
    allUsers.Add (cUser);
}

Although it works, but I think it is possible to shorten the code .. Anyone have any advice?

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
R-S
  • 151
  • 10
  • 1
    Start with how you would do this in t-sql. Now map that to linq. (you would use a inner join and in linq its the `.Join` extension). The general rule of thumb is if you can do it with a single sql statement you can also do it with a single linq statement. – Igor Jun 09 '21 at 14:19

1 Answers1

0

This query should be optimal:

var query =
    from like in _context.Likes.Where(x => x.AfazaId == id)
    from user in _context.User.Where(x => x.Id == like.Id).Take(1)
    select user;

var allUsers = await query.ToListAsync();
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32