开发者

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

  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 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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜