Lambda expression where column is equal to list it

2019-05-05 17:00发布

I have a general result having different columns including id column. I also have a List which has a set of id's. I want to get result where List item(id) matches the Id column value.

I tried doing this in a loop:

foreach(int Uid in idList)
{
    queryResults = queryResults.Where(security => security.id== Uid);
}  

But this gives me single record in queryResults which is for the last Uid in List. What I want is, records for all Uid's in List should be there in queryResults.

标签: c# linq lambda
1条回答
Rolldiameter
2楼-- · 2019-05-05 17:22

You will need to match the id of every item to the ids stored in your idList. This can be achieved by means of the Where-extension used on your queryResult in combination with the Contains-method used on the idList:

var idList = new List<int>{1, 2, 3, 4} // This is your list holding the ids
var result = queryResult.Where(security => idList.Contains(security.SecuritiesId));

This will check for every item of the queryResult whether its SecuritiesId is contained in the list containing the relevant ids.

查看更多
登录 后发表回答