Question

I have this method which needs to be called for different properties (returning IEnumerable<string>) like MyList for each child in Children

    public IEnumerable<string> GetMyListAggregatedValues()
    {
        var aggregatedValues = new List<string>();
        return Children.Aggregate(aggregatedValues , (current, child) => current.Union(child.MyList).ToList());
    }

One way to solve this is to call it for each of those properties against Children.

So my questions is, is there a way to somehow avoid this repetitive code and dynamically pass property name (without using reflection, which would be an overkill I think).

So, statically, these calls will be made like

GetMyListAggregatedValues();
GetAnotherListAggregatedValues();

And what I am after (if possible)

GetAggregatedValues(_SOMETHING_.MyList);
Was it helpful?

Solution

If all of the properties in question implement IEnumerable<string> then it's pretty easy. Just package the "given a child, access one of its properties" logic into a lambda:

public IEnumerable<string> 
GetAggregatedValues(Func<Child, IEnumerable<string>> selector)
{
    var aggregatedValues = new List<string>();
    return Children.Aggregate(
        aggregatedValues , 
        (current, child) => current.Union(selector(child)).ToList()
    );
}

and call it with

GetAggregatedValues(c => c.MyList);

You can even generalize this further by making string a type argument wherever it appears in the above code, then the same construct would also work for IEnumerable<int> etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top