Lambda Expression Select Only Certain Items from Collection
I have this foreach loop that is looping through a UserTaskQueueJoint Entity. This entity has three fields
UserTaskQueueJoinID
UserID
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 ad开发者_StackOverflowditional 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);
}
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()
.
Would a .SelectMany()
work for you here? Not knowing exactly what your data structure looks like...
DataContext.UserTaskQueueJoin
.Where(x => x.UserID == {someuserid])
.SelectMany(y => y.Tasks);
Looks like you want a Contains
query:
var taskIds = UserTaskQueueJoin.Select( x=> x.TaskQueueID).ToArray();
_query = _query.Where(x => taskIds.Contains(x.AssignedToTaskQueueID));
精彩评论