Reputation: 48537
Here is what I currently have:
from s in domainThreads.Values
where (s.IsAvailable)
select s;
but I'm still learning Linq and believe that I can get it all on one line. Does the following look correct?
domainThreads.Values.Where(s => s.IsAvailable).Any();
Do I need the .Any()
?
Upvotes: 2
Views: 98
Reputation: 9129
It looks but is not the same. The result is boolean and returns true if the collection contains any elements.
You could write something like this, but is it really worth the effort?
var result = domainThreads.Values.Where(s => s.IsAvailable).Select(s => s);
or shorter:
var result = domainThreads.Values.Where(s => s.IsAvailable);
EDIT: if you just want to have one line of code you can also write:
from s in domainThreads.Values where s.IsAvailable select s;
It's much more readable and generates to the same code in the end.
Upvotes: 0
Reputation: 27085
Any()
returns a boolean that is true if the result contains one or more items.
var elements = from s in domainThreads.Values
where (s.IsAvailable)
select s;
//elements now contains a list of objects.
This is equivalent to:
elements = domainThreads.Where(s => s.IsAvailable);
Upvotes: 1
Reputation: 30095
If you call Any()
it returns bool
which indicates that you have at least one item.
domainThreads.Values.Where(s => s.IsAvailable);
Upvotes: 1
Reputation: 2896
Try this
var obj = domainThreads.Values.Where(s => s.IsAvailable == true).Select(o => o);
Upvotes: 1
Reputation: 62484
Any() returns a bool
value, but your original query returns a data set. So just use Where()
var result = domainThreads.Values.Where(s => s.IsAvailable);
Any()
would be helpful when you just need ensure that at least single item satisfies a condition
Upvotes: 1
Reputation: 19305
domainThreads.Values.Where(s => s.IsAvailable)
is enough.
Upvotes: 1
Reputation: 14757
You don't need the Any()
-- that will return a bool
indicating if any of elements satisfy the condition.
Instead, just do:
domainThreads.Values.Where(s => s.IsAvailable)
Upvotes: 1
Reputation: 498942
The two are not equivalent.
The first returns all Values
where s.IsAvailable
.
The second returns whether there are any such values.
A correct conversion is:
domainThreads.Values.Where(s => s.IsAvailable)
Which translates to:
domainThreads.Values.Where(s => s.IsAvailable).Select(s => s)
Which is what the original query gets transformed to anyways.
Upvotes: 2
Reputation: 129792
Any()
returns a boolean indicating whether or not there are any entities in the given set.
The equivalent of your original LINQ expression would simply be:
domainThreads.Values.Where(s => s.IsAvailable)
Upvotes: 3