我正在撰写一个简单的联系管理应用程序。在我的域模式中,我在联系人和标签之间有很多关系。现在我的mvc内部我需要询问用户选择的标签并返回所有其标签与用户提供的标签匹配的联系人。
例如,如果联系najam有3个标签 - " author"," blogger"," subscriber"和管理员选择"作者"和"订户"搜索比najam应该在结果中。
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; }
}
我一直在玩LinqPad linq Expression,但无法找到解决方案。我尝试在where子句中使用contains和ant。
答案 0 :(得分:0)
假设您有以下联系人:
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" }
}
},
};
以下搜索标记:
var tagsToSearch = new Collection<Tag>()
{
new Tag() {Name = "author"},
new Tag() {Name = "blogger"}
};
Yo可以执行以下LINQ查询来搜索具有相关标签的联系人列表:
var searchResults = contacts.Where(c => c.Tags.Any(t=> tagsToSearch.Any(tts=>tts.Name == t.Name)));
如果您在Tag类上实施IEquatable<Tag>
,您也可以执行以下操作:
var searchResults = contacts.Where(c => c.Tags.Any(tagsToSearch.Contains));