Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 959
nhinkle Avatar asked Jul 16 '17 23:07

nhinkle


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

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);
like image 99
Nick Avatar answered Sep 21 '22 17:09

Nick