nhinkle
nhinkle

Reputation: 1157

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 f.a, f.b, or f.c. 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.

Upvotes: 16

Views: 907

Answers (1)

Nick
Nick

Reputation: 1038

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

Upvotes: 29

Related Questions