Search code examples
c#generic-listnested-generics

Searching a nested List<T>


I have this data structure:

class Conference 
{
    private List<List<string>>_orgs;
    public List<List<string>> Orgs
    {
       set { _orgs = value; } get { return _orgs; }
    }
}

Data in this collection:

List<string> sublist = new List<string>();
sublist.Add("university");
sublist.Add("organization");

List<List<string>> list = new List<List<string>>();
list.Add(sublist);

Then:

Conference c = new Conference();
c.Orgs = list;

I have collection of conference objects:

List<Conference> listConferences = new List<Conference>(); 
listConferences.Add(c);

I want search a string like "uni" and find collection of conference have orgs like "uni". How can I do this?


Solution

  • You can do this:

    var selection = listConferences
                    .Where(x => x.Orgs.SelectMany(y => y).Any(y => y.Contains("uni")))
                    .ToList();
    

    Note:

    the trailing ToList() might not be necessary depending on your needs (e.g. if you iterate selection only once you can skip it).