Lambda expression to match in ICollection navigation property with an array

436 views Asked by At

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?

1

There are 1 answers

1
Navoneel Talukdar On

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));