3

I am trying to design a generic method, the method deals with a collection of say employees. The employee class has around 5 to 10 attributes. I want to be able to pass a filter and get back a (generic) a collection class EmployeeSummary with some of the attributes of the Employee class.

public T GetFilteredSubset<T>(Somecollection employeeList, filter)

The method must be able to apply the filter dynamically to this collection and return back a new projection of type T which would contain a subset of attributes of the parent class. I see other post about dynamically applying filters but unable to find any information on specifying the subset (is that even possible or am I going about this the wrong way). So for subset the caller will create a class whose attributes - name and type will match exactly those of the parent Employee class but only contain subset of attributes. The function needs to be able to apply the filter then based on the type T will return only those attributes to the caller.

Using VS 2010 , .Net 4.0, C# Thanks for your help / time

1 Answer 1

2

Not sure if this is the best answer but what about this:

public static IEnumerable<TSelect> 
           GetFilteredSubset<TEntity, TSelect>(IEnumerable<TEntity> collection,
                                               Func<TEntity, bool> filter)
        where TSelect : class, new()
    {
        IEnumerable<TSelect> result = collection.Where(filter)
            .Select(s => new TSelect().InjectFrom(s))
            .Cast<TSelect>();

        return result;
    }

InjectFrom is from the ValueInjecter library, which provides the mapping between the two types using conventions.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your input I am looking at Valueinjecter library and it looks promising

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.