Search code examples
c#listlinqentitywhere-clause

LINQ Where query with object list


I have a list of objects ListA with property Id and I have to make a query in a table that has a column Id and find the rows that the ids are the same. How exactly can I achieve that with a single query and not a foreach loop of listA?

Thank you for your time

foreach(var object in listA)
{
  context.Table.Where(x => x.id == object.Id)....
}

Solution

  • Looks like you want to return all rows from the table that have an ID contained in the list of objects with the same ID. The following will achieve this. I can modify my answer to suit your need. Just let me know if you are looking for something slightly different.

    void Main()
    {
        
        var listA = new List<A> { new A { Id = 1 }, new A { Id = 4 } };
        
        var results = context.Table
            .Where(t => listA.Select(l => l.Id).Contains(t.Id))
    }
        
    public class A
    {
        public int Id { get; set; }
    }