Lambda Expression Select Only Certain Items from Collection

12,837

Assuming I understood your question correctly, you can replace the whole loop with this:

var TaskQueueIds = _taskQueueJoin.Select(t => t.TaskQueueID).ToArray()
_query = _query.Where(x => TaskQueueIds.Contains(x.AssignedToTaskQueueID))

It gets all the task queue ids together first. Then it filters _query with a single .Where().

Share:
12,837
gevjen
Author by

gevjen

Updated on June 04, 2022

Comments

  • gevjen
    gevjen almost 2 years

    I have this foreach loop that is looping through a UserTaskQueueJoint Entity. This entity has three fields

    1. UserTaskQueueJoinID

    2. UserID

    3. TaskQueueID

    it has a navigation property to taskQueues and to Tasks

    I am running a foreach through these and only want to get the tasks out that are in the taskqueue. so as i go through this loop below i go through my foreach loop twice, the first time i get one task..then the second time through i get the additional two tasks, but it removes the first task. Im sure I am not supposed to be using a where clause, i think im should be using a select or a contains or an 'in' but Im stuck on how to implement.

    foreach (var _taskQueueJoin in UserTaskQueueJoin)
    {
    _query = _query.Where(x => x.AssignedToTaskQueueID == _taskQueueJoin.TaskQueueID);   
    }