简体   繁体   中英

How to pass a list to a LINQ query as search condition?

Right now, I could run a LINQ query like below:

 private Person PopulatePerson(Person person)
    {
        return (from er in context.Orders
               where er.personId == person.Id
                select new Person()
                {
                    Name = person.Name
                    Qty = er.OrderQty,
                }).FirstOrDefault();
    }

What if I pass a list of person to this method above to be like below? How do I change my query to iterate it?

 private List<Person> PopulatePerson(List<Person> persons)
    {

    }

I can foreach List<Person> , but it will connect to the db many times. Assuming want to take the first result. actually that is just an example. actually there are many duplicate child records in order and thus I just need to take the first records which I manage to get it. But what if I want to pass a list into the query to iterate inside the LINQ instead of writing a foreach outside.

Contains is suppported, so you need to select the identifier into a collection like array or list:

private IList<Person> PopulatePersons(IEnumerable<Person> persons)
{
    string[] allIds = persons.Select(p => p.Id).ToArray();
    return (from er in context.Orders
            where allIds.Contains(er.PersonId)
            join p in context.Persons on er.PersonId equals p.Id
            group new { Qty = er.OrderQty, Name = p.Name} by er.PersonId into PersonIdGroup
            select new Person()
            {
                Name = PersonIdGroup.First().Name,
                Qty = PersonIdGroup.Sum(x => x.Qty)
            }).ToList();
}

I assume that you want to return multiple persons then so not only one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM