简体   繁体   中英

C# re-use LINQ expression for different properties with same type

I have a class with several int properties:

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> . 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 :

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 . 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.

Is there any way to do this in 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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