简体   繁体   English

在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);

On the last line I want to pass in a parameter from somewhere else which will replace .AnotherRow 在最后一行,我想从其他地方传递参数,该参数将替换.AnotherRow

In other words, something like: 换句话说,类似:

.Sum(row => row. + myParameter);

Any ideas? 有任何想法吗? I get an error when I try the above. 尝试上述操作时出现错误。 Would appreciate any help. 将不胜感激。

You cannot pass something that would represent .AnotherRow , but you can pass a functor that picks the desired attribute from your object. 您不能传递表示.AnotherRow ,但可以传递从对象中选择所需属性的函子。

Let's say table is IEnumerable<MyClass> . 假设tableIEnumerable<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);

I think: 我认为:

someData = table.AsEnumerable()
    .Where(row => row.someRow.Equals("Something"))
g.Sum(row => Calculate(row => row.AnotherRow, row1 =>row1.AnotherRow));

Method Calculate: 方法计算:

 private double Calculate(double d1, double d2)
    {
        return d1 + d2;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM