Sudantha
Sudantha

Reputation: 16204

LINQ and Boolean Values

I have a LINQ Query which returns a Boolean.

     Boolean status=true;
     var s = from p in msg where p.Type == false select false;

im required to set status from the value from the LINQ query which is a boolean how to take a approach to this

If the LINQ query has a single false i need to return a false as Boolean thats what i need

Upvotes: 1

Views: 19488

Answers (2)

Chris
Chris

Reputation: 27599

At the moment assumign p has lots of msgs then s is going to be an enumerable with zero to lots of falses in. You might want to consider a different operator like

!msg.Any(x=>x.Type=false)

Or better thanks to Ray in comments:

msg.All(x => x.Type)

Any returns true if the condition is satisfied by anything in p. All returns true if the condition is satisfied in all of them (and will thus immediately return if it finds one that doesn't match).

Alternatively with your code you could just do:

status = s.Count()==0;

If your s is empty (no falses in it) then it will return true, if it has one or more falses it will return false.

Upvotes: 14

Samuel Slade
Samuel Slade

Reputation: 8613

So far as I understand the question, this all depends on what the purpose of your status flag is. Since the LINQ query will return an enumerable collection of boolean values, you will need to determine what the status flag should be assigned to based on this collection.

In this case, you will end up with an arbitrarily sized collection of false values. So if you wish status to be true if you have no false values, you simply need to query the size of the collection. i.e.:

status = s.Count() == 0;  // Note: This is an example using the System.Linq namespace

Upvotes: 0

Related Questions