[英]C# re-use LINQ expression for different properties with same type
I have a class with several int
properties: 我有一个包含几个
int
属性的类:
class Foo
{
string bar {get; set;}
int a {get; set;}
int b {get; set;}
int c {get; set;}
}
I have a LINQ expression I wish to use on a List<Foo>
. 我有一个LINQ表达式,我希望在
List<Foo>
。 I want to be able to use this expression to filter/select from the list by looking at any of the three properties. 我希望能够通过查看三个属性中的任何一个来使用此表达式从列表中过滤/选择。 For example, if I were filtering by
a
: 例如,如果我按
a
过滤:
return listOfFoo.Where(f => f.a >= 0).OrderBy(f => f.a).Take(5).Select(f => f.bar);
However, I want to be able to do that with any of fa
, fb
, or fc
. 但是,我希望能够使用
fa
, fb
或fc
任何一个。 Rather than re-type the LINQ expression 3 times, I'd like to have some method which would take an argument to specify which of a, b, or c I want to filter on, and then return that result. 我不想重新键入3次LINQ表达式,而是希望有一些方法可以使用参数来指定我想要过滤的a,b或c中的哪一个,然后返回该结果。
Is there any way to do this in C#? 有没有办法在C#中做到这一点? Nothing immediately comes to mind, but it feels like something that should be possible.
没有什么可以立刻浮现在脑海中,但感觉应该是可能的。
IEnumerable<string> TakeBarWherePositive(IEnumerable<Foo> sequenceOfFoo, Func<Foo, int> intSelector) {
return sequenceOfFoo
.Where(f => intSelector(f) >= 0)
.OrderBy(intSelector)
.Take(5)
.Select(f => f.bar);
}
Then you would call as 然后你会打电话给
var a = TakeBarWherePositive(listOfFoo, f => f.a);
var b = TakeBarWherePositive(listOfFoo, f => f.b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.