在Linq中传递参数 [英] Passing a parameter within Linq
问题描述
我在方法中包含以下代码:
I have the following code within a method:
someData = table.AsEnumerable()
.Where(row => row.someRow.Equals("Something"))
.Sum(row => row.AnotherRow);
在最后一行,我想从其他地方传递一个参数,该参数将替换.AnotherRow
On the last line I want to pass in a parameter from somewhere else which will replace .AnotherRow
换句话说,是这样的:
.Sum(row => row. + myParameter);
有什么想法吗?尝试上述操作时出现错误.不胜感激.
Any ideas? I get an error when I try the above. Would appreciate any help.
推荐答案
您不能传递表示.AnotherRow
的内容,但是可以传递函子,该函子从对象中选择所需的属性.
You cannot pass something that would represent .AnotherRow
, but you can pass a functor that picks the desired attribute from your object.
让我们说table
是IEnumerable<MyClass>
.然后,您可以执行以下操作:
Let's say table
is IEnumerable<MyClass>
. Then you can do this:
int SumSelected(Func<MyClass,int> attrSelector) {
return table.AsEnumerable()
.Where(row => row.someRow.Equals("Something"))
.Sum(row => attrSelector(AnotherRow));
}
现在,您可以使用选择器"来调用此方法,该选择器指定要添加的属性,如下所示:
Now you can call this method with a "selector" that designates the attributes to be added up, as follows:
var totalCustomers = SumSelected(obj => obj.CustomerCount);
var totalStores = SumSelected(obj => obj.StoreCount);
这篇关于在Linq中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!