Hierarchical Object Filter

1

I have an asp.net MVC 4.5 C # razor screen typed by a main class:

public class ClassePaiDTO 
{
    public virtual ICollection<Filho1DTO> Filho1s { get; set; }
    public virtual ICollection<Filho2DTO> Filho2s { get; set; }

    //codigo Filter imaginado
    private FilterSelected()
    {
       this.Filho1s =  this.Filho1s.Where(s => s.Selected).ToList();
       this.Filho2s =  this.Filho2s.Where(s => s.Selected).ToList();
    }
}

public class Filho1DTO 
{
    public bool Selected { get; set; }
    public virtual ICollection<Neto1DTO> Neto1s { get; set; }
}

public class Filho2DTO
{
    public bool Selected { get; set; }
}

public class Neto1DTO 
{
    public bool Selected { get; set; }
}

After executing a POST, in my controller, I would like to execute a filter to get only what are marked as true. Ex:

objClassePaiDTO.FilterSelected();

After that, you would only use an AutoMapper to transform into Entity. I tried to use a resolver to make a filter, but it is not always that I need it, that is, only in the same post on my screen.

As the system is full of "parent classes". What is the clean and semantic implementation required for this situation?

At first I had thought of creating an abstract class:

  • With a bool property named Selected;
  • With an abstract method called Filter ();
  • Every class that needs to be filtered I would inherit from this class.

But I think I got into design and I could not get a common denominator.

Then I thought about creating a reflection for:

When the parent class calls the FilterSelected () method, it would navigate through the properties by checking without having lists of children, grandchildren, and the like filtering everything in front.

I confess that this last approach I found a bit extreme, but if it worked, it would work generically for other Pai classes of the system.

    
asked by anonymous 17.03.2015 / 13:57

1 answer

1

I would create an abstract class like this below where Father, Children and grandchildren would inherit:

public abstract class SortBase : ISortBase
{
    #region ISortBase Members

    public IList<ISortBase> ChildList { get; set; }
    public bool Selected { get; set; }

    public virtual void Sort()
    {
        ChildList = ChildList.Where(x => x.Selected).ToList();
        foreach (var sortBase in ChildList)
            sortBase.Sort();

    }

    #endregion
}

Now if your parent / child class and etc have more than one children list that needs to be sorted as well, I would use reflection to call the Sort method of these SortBase collections.

    
17.03.2015 / 17:08