简体   繁体   中英

Lambda Expression for Not In a Collection

I have 3 tables

eTrip

Country | eProfile

eProfile

Documents (collection of Document)

Documents

Type | ExpiryDate | Country

I am trying to get a collection of eTrips in a search api. There are several conditions that need to be met for an eTrip.

Each employee can hold multiple documents (visas, passports, etc). For an eTrip to be valid we need to make sure the eTrip.Country != the country of a valid passport (future expiry date) document.

How can we write a lambda expression to accomplish this?

The code that I have so far is something like this

    var query = context.eTrip.AsQueryable();
    query = query.Where(e => e.validTrip == true);
    var docs = query.Select(e => e.eProfile.Documents);
        foreach (Documents d in docs)
        {
            if (d.DocumentTypeCode == "Passport" && d.ExpiryDate != null && d.ExpiryDate > DateTime.Now)
            {
               query = query.Where(e => e.Country != d.Country);
            }
        }

I need to write the filter for the country now and I am not sure how we can do it for a collection.

您可以使用文档上的Any子查询扩展Where子句

query = query.Where(e => e.validTrip == true && e.eProfile.Documents.Any(a=>a.DocumentTypeCode == "Passport" && a.ExpiryDate.HasValue && a.ExpiryDate.Value > DateTime.Now && e.Country!=d.Country));

Try that:

        // your part
        var query = context.eTrip.AsQueryable();
        query = query.Where(e => e.validTrip == true);
        var docs = query.Select(e => e.eProfile.Documents);

        // get countries for which there are no documents with future date
        var myCountryQuery = query.Where(x => !docs
            .Where(d => d.DocumentTypeCode == "Passport" && d.ExpiryDate != null && d.ExpiryDate > DateTime.Now)
            .Any(d => d.Country != x.Country)
            );

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