Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Linq as an IF - Condition

I got a little linq query searching for a customer in a database:

var query =
   from c in database.customer
   where c.ID == input
   select c;

Every customer has an ID, which in this case is set by an user-"input"

All customers in database are from "Germany" but some shall be copied into the database with a different value for country ("England" instead of "Germany")

Now, before adding them to the database directly, I want to check if there is already an "english version" of this customer in the database.

if (query.Where(c => c.country == "England"))
   //do nothing
else 
   //add the customer with c.country = "England"

The problem is that this is not a regular if-statement.

Is there a possible way to achieve what I want to express in this if-condition?

Thanks

like image 293
reveN Avatar asked Jan 04 '23 17:01

reveN


1 Answers

just change condition to

if (query.Any(c => c.country.Equals("England")))
   //do nothing
else 
   //add the customer with c.country = "England"

Linq method Where returns IEnumerable value wchich can't be automatically converted into bool value. Methods like Any or All returns true or false based on whether condition is true for at least one element in collection or all of them respectively.

like image 177
Jaroslav Kadlec Avatar answered Jan 07 '23 08:01

Jaroslav Kadlec