简体   繁体   中英

Lambda expression to match in ICollection navigation property with an array

I have the following code-first entity -

public class Contact
{
    public Contact()
    {
        this.Tags = new HashSet<Tag>();
    }

    public int ContactId { get; set; }
    public string ContactName { get; set; }     
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public Tag()
    {
        this.Contacts = new HashSet<Contact>();
    }

    public int TagId { get; set; }
    public string TagName { get; set; }
    public virtual ICollection<Contact> Contacts { get; set; }
}

I would like to search a contact based on Tags property from an string array. Something like the following-

//string[] tags
Select from Db.Contacts where any Tag matched with any item in arrTags

I could not figure out how it can be done in lambda. Any help?

You can try this

var query = ctx.Contacts
            .SelectMany(x => x.Tags)
            .Where(z => YourTagArray.Contains(z.TagName);

EDIT:

To get matching contacts

var query = ctx.Contacts.Where(x => x.Tags.Any(t => YourTagArray.Contains(t.TagName));

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