0

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;}
}
CodeMilian
  • 1,262
  • 2
  • 17
  • 41

2 Answers2

2

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.

Heinz Kessler
  • 1,610
  • 11
  • 24
  • Thank you for the explanation that makes sense in regards to the use of count. However, I did change my query to the above suggestion but it throws the following error: "The method FindAll is not supported in the expression tree" – CodeMilian May 27 '19 at 20:14
  • Maybe this is helpful: https://stackoverflow.com/questions/1938204/linq-where-vs-findall – Heinz Kessler May 28 '19 at 05:17
0

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));

spzvtbg
  • 964
  • 5
  • 13