我有一个有几个int属性的类:
class Foo
{
string bar {get; set;}
int a {get; set;}
int b {get; set;}
int c {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我有一个LINQ表达式,我希望在一个List<Foo>.我希望能够通过查看三个属性中的任何一个来使用此表达式从列表中过滤/选择.例如,如果我按a以下方式过滤:
return listOfFoo.Where(f => f.a >= 0).OrderBy(f => f.a).Take(5).Select(f => f.bar);
Run Code Online (Sandbox Code Playgroud)
不过,我希望能够做到这一点任何的f.a,f.b或f.c.我不想重新键入3次LINQ表达式,而是希望有一些方法可以使用参数来指定我想要过滤的a,b或c中的哪一个,然后返回该结果.
有没有办法在C#中做到这一点?没有什么可以立刻浮现在脑海中,但感觉应该是可能的.
Nic*_*ick 29
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);
}
Run Code Online (Sandbox Code Playgroud)
然后你会打电话给
var a = TakeBarWherePositive(listOfFoo, f => f.a);
var b = TakeBarWherePositive(listOfFoo, f => f.b);
Run Code Online (Sandbox Code Playgroud)