Jim Jim - 17 days ago 6
C# Question

Linq where list contains one of list

I have and array object that is a

List<ContactModel> contactList;

public class ContactModel
{
public string CustomKey { get; set; }
public string[] ContactGroups { get; set; }
}


So objects would be

{"1", {"Group A"} }
{"2", {"Group A", "Group B", "Group C"} }
{"3", {"Group C", "Group D"} }
{"4", {"Group A", "Group B", "Group C", "Group D"} }


The ContactGroups contains a list of groups {"Group A", "Group B", "Group C","Group D"}
that a given contact exists in.
I can get results for one group by using the following.

var selectedContracts =
from contact in contacts
where contact.ContactGroups.Contains("Group A")
select new { contact.CustomKey, contact.ContactGroups };


Is there a way to get a list back with all objects containing one of a list of objects.

var selectedContracts =
from contact in contacts
where contact.ContactGroups.Contains("Group A", "Group B")
select new { contact.CustomKey, contact.ContactGroups };


I need to get back object 1,2,4.

Answer

Target method:

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

Examples of usage:

void Run()
{
    Initial();
    var selectedContacts = SelectContacts(contactList, 
      new[] { "Group A", "Group B" });
    PrintContacts(selectedContacts);
}

Help methods:

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