Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression where column is equal to list items

Tags:

c#

lambda

linq

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.

like image 272
Nitish Avatar asked Feb 18 '23 15:02

Nitish


1 Answers

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.

like image 132
Spontifixus Avatar answered Mar 05 '23 07:03

Spontifixus