reveN
reveN

Reputation: 642

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

Upvotes: 4

Views: 4217

Answers (1)

Jaroslav Kadlec
Jaroslav Kadlec

Reputation: 2543

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.

Upvotes: 9

Related Questions