c# - Query to filter contacts with given tags while having many to many relation between entities -
c# - Query to filter contacts with given tags while having many to many relation between entities -
i writing simple contact management app. in domain mode have many many relation between contacts , tags. within mvc in need inquire take user selected tags , homecoming contacts have of tags match user supplied tags.
for illustration if contact najam has 3 tags - "author", "blogger", "subscriber" , admin chooses "author" , "subscriber" search najam should in results.
public class tag { public tag() { createdon = datetime.now; } public int tagid { get; set; } public string name { get; set; } public datetime createdon { get; set; } public virtual icollection<contact> contacts { get; set; } } public class contact { public contact() { isnewslettersubscriber = true; createdon = datetime.now; } public int contactid { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string email { get; set; } public string organization { get; set; } public string cellphone { get; set; } public string designation { get; set; } public string address { get; set; } public string phonenumber { get; set; } public bool isnewslettersubscriber { get; set; } public string twitter { get; set; } public string facebook { get; set; } public datetime createdon { get; set; } public virtual icollection<tag> tags { get; set; } }
i have been playing linqpad linq look couldn't figure out solution this. tried using contains , ant within clause.
assuming have next contacts:
var contacts = new list<contact>() { new contact(){ firstname = "najam", tags = new collection<tag>() { new tag(){ name = "author" }, new tag(){ name = "blogger" }, new tag(){ name = "subscriber" } } }, new contact(){ firstname = "mick", tags = new collection<tag>() { new tag(){ name = "author" }, } }, new contact(){ firstname = "ryan", tags = new collection<tag>() { new tag(){ name = "subscriber" } } }, };
and next search tags:
var tagstosearch = new collection<tag>() { new tag() {name = "author"}, new tag() {name = "blogger"} };
yo can next linq query search list of contacts have tags in question:
var searchresults = contacts.where(c => c.tags.any(t=> tagstosearch.any(tts=>tts.name == t.name)));
if implement iequatable<tag>
on tag class can do:
var searchresults = contacts.where(c => c.tags.any(tagstosearch.contains));
c# linq
Comments
Post a Comment