对于具有相同类型的不同属性,C#重用LINQ表达式

nhi*_*kle 16 c# linq

我有一个有几个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.bf.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)

  • `Func <Foo,int>`表示"一个函数,它接受一个类型为`Foo`的值,并返回一个类型为`int`的值." 在你给出的例子中,`f => fa`和`f => fb`都是`Func <Foo,int>`.你也可以做一些更奇特的事情,比如`f => fa + 1000`,或者像`f => 1000`这样的东西 - 所有这些都是`TakeBarWherePositive`的有效参数. (5认同)