samedi 6 janvier 2018

Intersection of two Lists of Objects

In a WPF/C# project, I've got about 50 reports which are actually Views imported by Entity Framework from a Database. Now, in each of these reports, I need to implement various filters that'd filter the report based on parameters like Date.

All the reports derive from a base generic class ReportsBaseViewModel.

    private BindableCollection<T> _report;

    //The report that's displayed
    public BindableCollection<T> Report
    {
        get
        {
            return _report;
        }
        set
        {
            if (value == _report)
            {
                return;
            }
            _report = value;
            NotifyOfPropertyChange();
        }
    }

    protected BindableCollection<T> GetIntersect(IEnumerable<T> set) => Report?.Intersect(set)?.ToBindableCollection();

Here's the code I'm using in one of the ViewModels for report:

    private void FilterReportByDate()
    {
        if ((StartDate == null) || (EndDate == null))
        {
            return;
        }
        Report = GetIntersect(_uow.purchasetaxreport.FilterByDate((DateTime)StartDate, (DateTime)EndDate));
    }

    private void FilterReportByTaxType()
    {
        if (SelectedTaxType == null)
        {
            return;
        }

        Report = GetIntersect(_uow.purchasetaxreport.FindWhere(c => c.taxtype == SelectedTaxType.taxtype, RecordsCount));
    }        

    private void FilterReportBySupplier()
    {
        if (SelectedSupplier == null)
        {
            return;
        }

        Report = GetIntersect(_uow.purchasetaxreport.FindWhere(c => c.name == SelectedSupplier.ID, RecordsCount));
    }

    public override void Populate()
    {
        Report = _uow.purchasetaxreport.FetchTopRecords(RecordsCount).ToBindableCollection();
        ApplyAllFilters?.Invoke();
    }

In its ctor, I have this:

    ApplyAllFilters += FilterReportByDate;
    ApplyAllFilters += FilterReportByTaxType;
    ApplyAllFilters += FilterReportBySupplier;

To simplify things, when a filter is applied, records are fetched from the DB, and then filters are applied by intersection. Problem is, intersection doesn't work, obviously, because there's no EqualityComparer. Now, in order to design a EqualityComparer that'd work across the board with all reports, I'd need a generic EqualityComparer which would involve heavy use of Reflection, which I'd like to avoid, if possible.

Is there any other way to achieve what I'm trying to without the help of Reflection?





Aucun commentaire:

Enregistrer un commentaire