2022-05-31

Filter (Triple) Nested Collection using Linq C#

I need to filter a List of collections > Repos > Workflows and return the result in the same format

Hopefully the example is fairly clear please shout if you think it needs more detail.

    // All classes have a property 'Name'
    // Filter along the branch for any that match and return only the matching items

    List<Collection> AllCollections = new List<Collection>();
    Collection CollectionA = new Collection();
    Collection CollectionB = new Collection();
    CollectionA.Repos = new List<Repo>{new Repo{Name = "FirstRepo", Workflows = new List<Workflow>{new Workflow{Name = "CI-CD"}, new Workflow{Name = "Tests"}, new Workflow{Name = "First-Ops"}}}, new Repo{Name = "SecondRepo", Workflows = new List<Workflow>{new Workflow{Name = "CI-CD"}, new Workflow{Name = "Testing"}, new Workflow{Name = "Second-Ops"}}}, new Repo{Name = "ThirdRepo", Workflows = new List<Workflow>{new Workflow{Name = "CI-CD"}, new Workflow{Name = "Testers"}, new Workflow{Name = "Third-Ops"}}}};
    CollectionB.Repos = new List<Repo>{new Repo{Name = "FronEndUI", Workflows = new List<Workflow>{new Workflow{Name = "CD"}, new Workflow{Name = "UI-Tests"}, new Workflow{Name = "first-Op"}}}, new Repo{Name = "API", Workflows = new List<Workflow>{new Workflow{Name = "CI"}, new Workflow{Name = "Testing"}, new Workflow{Name = "second-Op"}}}, new Repo{Name = "VisualBasic", Workflows = new List<Workflow>{new Workflow{Name = "Deploy"}, new Workflow{Name = "Copy"}, new Workflow{Name = "third-Op"}}}};
    AllCollections.Add(CollectionA);
    AllCollections.Add(CollectionB);
    // Filter 
    string FilterString = "";  // string FilterString = "Copy" , should return  AllCollections > CollectionB > Repo VisualBasic > Workflow Deploy
    // Result should be List of collections > List of Repos > List of workflows
    List<Collection> result = AllCollections.SelectMany(c => c.Repos.Where(r => r.Name.Contains(FilterString.ToLower())).ToList().SelectMany(w => w.Workflows.Where(w => w.Name.Contains(FilterString)))).ToList();
    // Dont know how to show nested list in a table sorry
    // This is returning the workflows but not the parent Repo and Repo's Parent, The Collection



public class Collection
{
    public string Name { get; set; }

    public List<Repo> Repos { get; set; }
}

public class Repo
{
    public string Name { get; set; }

    public List<Workflow> Workflows { get; set; }
}

public class Workflow
{
    public string Name { get; set; }
}

See it here dotnetfiddle



No comments:

Post a Comment