Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values via a Lambda Expressions?

Tags:

c#

.net

lambda

I am aware of the following quote:

The reason is that a lambda expression can either be converted to a delegate type or an expression tree - but it has to know which delegate type. Just knowing the signature isn't enough.

Trouble is I am still stuck on how to resolve my problem.

Can someone tell if the below is at all possible?

bool isStaff = () => { return selectedPerson.PersonType == "Staff"; };

Error:

Cannot convert lambda expression to type 'bool' because it is not a delegate type

I understand the error, but I really want to know how to fix this issue as I have rebounded off this error many times and simply not learnt to how properly use lamda expressions as far as value assignment is concerned.

Thanks for the quick replies fellas:

IMO, it would be awesome of the below was possible:

bool isStaff = (selectedPerson, bool) => { return selectedPerson.PersonType == "Staff"; };

Lol, I don't think that works but is beautiful in line code, to me that looks awesome and what I expect. The answers below seem to suggest otherwise lol!

like image 368
IbrarMumtaz Avatar asked Dec 10 '22 03:12

IbrarMumtaz


2 Answers

The problem is that the lambda returns a bool when it is evaluated, but it is not a bool itself.

You can do the following:

Func<bool> func = () => { return selectedPerson.PersonType == "Staff"; };
bool isStaff = func();

This assigns the lambda to a variable, which can then be used to invoke the lambda, and return the desired bool value.

like image 72
Andrew Cooper Avatar answered Dec 25 '22 23:12

Andrew Cooper


bool isStaff = selectedPerson.PersonType == "Staff";

or

Func<Person, bool> isStaffDelegate = selectedPerson => 
                                         selectedPerson.PersonType == "Staff"; 
bool isStaff = isStaffDelegate(selectedPerson); 
like image 21
albertjan Avatar answered Dec 26 '22 00:12

albertjan