I'm trying to optimize the following routine so that it only uses one database query instead of multiple but the filter (loop conditions) don't seem to be applied as all messeges are fetched.
public async Task<List<Message>> GetInboxMessegesFromUser(string inboxUser, List<string> senders)
{
// Doesn't work
var query = from m in _context.Messeges where m.ToUser == inboxUser select m;
foreach (string sender in senders)
{
query.Where(m => m.FromUser == sender);
}
return await query.ToListAsync();
// Old code
List<Message> messeges = new List<Message>();
foreach (string sender in senders)
{
messeges.AddRange(await _context.Messeges.Where(m => m.FromUser == sender && m.ToUser == inboxUser).ToListAsync());
}
return messeges;
}
How to add a dynamic number of conditions to a LINQ query before executing it so that a O(N*M) turns into O(N) ?