Why Use a Predicate in C# Instead of Just a Lambda Expression?

0
0
Asked By RandomCoder123 On

Hey everyone! I'm diving into Predicates in C# and I'm a bit puzzled. I've got some code where I create a List of integers and I use a Predicate to find numbers greater than or equal to ten. But I wonder, why is it better to define a Predicate variable instead of just passing a lambda expression directly into the FindAll method? Any insights would be awesome!

1 Answer

Answered By CodeNinja88 On

A predicate is basically a function that returns true or false based on its input. You could totally just use a lambda directly in FindAll, like this:

```csharp
List higherThanTen = numbers.FindAll(x => x >= 10);
```
But having a Predicate makes it reusable, and if your logic gets complex, it helps to keep the code clean.

LearningPython99 -

Exactly! I thought it was just about reusability too. Thanks for breaking that down!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.