Reputation: 1290
I have a find query that when from this
!CurrentUser.SentMatchRequest.Contains(OtherProfile.userId)
To this
CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0
However, the query fails by stating .count is not supported. Before the collection used to be a simple string array and now it changed to a complex object
public class info
{
public string Id {get;set;}
public DateTime TimeStamp {get;set;}
}
Upvotes: 0
Views: 268
Reputation: 1034
You can use (Count with () will iterate one more time over your collection) .Count() == 0; or Count() == 0; instead but is realy better to use .Any(x => x.Id.Equals(OtherProfile.userId));
Upvotes: 0
Reputation: 1670
If you want to test if your query's result contains at least one element, better use Any()
, like so:
Instead of...
CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0
better use...
!CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Any()
If you really need the count, you can get it like this:
CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).ToList().Count==0
The reason is, that IEnumerable<T>
can be used to iterate through a collection, but the number of elements in the collection remains unknown until you reach the end.
T get the count of elements, you must iterate through the whole collection, that's what happens with the ToList()
method, it forces LINQ to exactly do this.
If you only need to know, if the collection contains elements at all, this apporach is inefficient. Any()
however, does what you need: It checks, if the collection contains at least one element, so this operation does not have t iterate through the whole collection.
Upvotes: 2