我有和数组对象是
List<ContactModel> contactList;
public class ContactModel
{
public string CustomKey { get; set; }
public string[] ContactGroups { get; set; }
}
所以对象就是
{"1", {"Group A"} }
{"2", {"Group A", "Group B", "Group C"} }
{"3", {"Group C", "Group D"} }
{"4", {"Group A", "Group B", "Group C", "Group D"} }
ContactGroups包含一个组列表{&#34; A组&#34;,&#34; B组&#34;&#34; C组&#34;&#34; D组&#34; } 给定的联系人存在于。 我可以使用以下内容获得一组的结果。
var selectedContracts =
from contact in contacts
where contact.ContactGroups.Contains("Group A")
select new { contact.CustomKey, contact.ContactGroups };
是否可以使用包含对象列表之一的所有对象来获取列表。
var selectedContracts =
from contact in contacts
where contact.ContactGroups.Contains("Group A", "Group B")
select new { contact.CustomKey, contact.ContactGroups };
我需要找回对象1,2,4。
答案 0 :(得分:2)
目标方法:
public static IEnumerable<ContactModel> SelectContacts(
List<ContactModel> contacts, string[] targetGroups)
{
return from contact in contacts
where targetGroups.Any(targetGroup =>
contact.ContactGroups.Contains(targetGroup))
select contact;
}
用法示例:
void Run()
{
Initial();
var selectedContacts = SelectContacts(contactList,
new[] { "Group A", "Group B" });
PrintContacts(selectedContacts);
}
帮助方法:
void Initial()
{
contactList = new List<ContactModel>
{
new ContactModel
{
CustomKey = "1",
ContactGroups = new[] { "Group A" }
},
new ContactModel
{
CustomKey = "2",
ContactGroups = new[] { "Group A", "Group B", "Group C" }
},
new ContactModel
{
CustomKey = "3",
ContactGroups = new[] { "Group C", "Group D" }
},
new ContactModel
{
CustomKey = "4",
ContactGroups = new[] { "Group A", "Group B", "Group C", "Group D" }
},
};
}
void PrintContacts(IEnumerable<ContactModel> contacts)
{
foreach (var selectedContract in contacts)
Console.WriteLine(selectedContract.CustomKey);
}
答案 1 :(得分:1)
返回1,2和4:
var objects = new string[] { "Group A", "Group B" };
var selectedContacts = contactList.Where(contact => objects
.Any(obj => contact.ContactGroups.Contains(obj)));
答案 2 :(得分:0)
不确定这是否是您正在寻找的
测试:
var contactList = new List<ContactModel> { new ContactModel {CustomKey = "1", ContactGroups = new[]{"Group A"} },
new ContactModel {CustomKey ="2", ContactGroups = new[]{"Group A", "Group B", "Group C"} },
new ContactModel {CustomKey ="3",ContactGroups = new[] {"Group C", "Group D"} },
new ContactModel {CustomKey ="4", ContactGroups = new[]{"Group A", "Group B", "Group C", "Group D"}},
new ContactModel {CustomKey ="5", ContactGroups = new[]{"Group A", "Group C", "Group D"}},
new ContactModel {CustomKey ="6", ContactGroups = new[]{ "Group D"}},
new ContactModel {CustomKey ="7", ContactGroups = new[]{"Group C"}},};
var CheckFor = new List<string>{"Group A", "Group B"};
var selectedContracts =
from contact in contactList
where contact.ContactGroups.Any(x => CheckFor.Contains(x))
select new { contact.CustomKey, contact.ContactGroups };