Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a recursive object?

Tags:

c#

In my current project, a method I don't control sends me an object of this type:

public class SampleClass
{
    public SampleClass();

    public int ID { get; set; }
    public List<SampleClass> Items { get; set; }
    public string Name { get; set; }
    public SampleType Type { get; set; }
}

public enum SampleType
{
    type1,
    type2,
    type3
}

I display those data in a TreeView, but I would like to display only the path ending with SampleClass objects having their Type property set to type3, no matter the depth of this leaf.

I have absolutely no clue on how to do that, can someone help me ?

Thanks in advance !

Edit

To explain the problem I meet with the solutions proposed by Shahrooz Jefri and dasblinkenlight, here is a picture. The left column is the original data, without filtering, and the right one is the data filtered. Both methods provide the same result. In red is the problem.

enter image description here

like image 839
Shimrod Avatar asked Oct 22 '22 17:10

Shimrod


2 Answers

Use this Filter method:

public void Filter(List<SampleClass> items)
{
    if (items != null)
    {
        List<SampleClass> itemsToRemove = new List<SampleClass>();

        foreach (SampleClass item in items)
        {
            Filter(item.Items);
            if (item.Items == null || item.Items.Count == 0)
                if (item.Type != SampleType.type3)
                    itemsToRemove.Add(item);
        }

        foreach (SampleClass item in itemsToRemove)
        {
            items.Remove(item);
        }
    }
}
like image 62
david.s Avatar answered Nov 01 '22 10:11

david.s


In addition to initially determining which items to show, if the datasize is substantial and you expect users to frequently collapse and expand sections then filtering after every click my result in slow ui response.

Consider the Decorator pattern or some other way of tagging each node with relevant info so that the filtering is not required after every click.

like image 24
Miserable Variable Avatar answered Nov 01 '22 09:11

Miserable Variable