[英]Passing property name to aggregate
I have this method which needs to be called for different properties (returning IEnumerable<string>
) like MyList
for each child in Children
我有这个方法,需要为孩子Children
每个孩子调用不同的属性(返回IEnumerable<string>
),如MyList
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);
If all of the properties in question implement IEnumerable<string>
then it's pretty easy. 如果所讨论的所有属性都实现了IEnumerable<string>
那么它非常简单。 Just package the "given a child, access one of its properties" logic into a lambda: 只需将“给定一个孩子,访问其中一个属性”逻辑打包成一个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. 您甚至可以通过将string
作为类型参数进一步概括,无论它出现在上面的代码中,那么相同的构造也适用于IEnumerable<int>
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.