Query Operators

It's not our job as a developer to memorize all the operators, but know they exist and when to use to solve the problem.

Three quantifiers operators in LINQ:

  • Any = to check if one object is matched
  • All = to check if all objects are matched
  • Contains = to check if something exists

Let's try in code.

Any operators.

Console.WriteLine(birds.Any(b => b.Name == "Beo"));
// return true

Contains operators.

var sparrow = new Bird {  Name = "sparrow", Color = "Red", Sightings = 3};
Console.WriteLine(birds.Contains(sparrow));
// return false

All operators.

Console.WriteLine(birds.All(b => b.Name != "Beo"));
// return false

It would be dependent on how many objects in collection and how likely the condition will pass or fail.

When anyis called on a collection, it evaluates the predicate on each element until one of them is passes and stop evaluating. While allfinds an element that doesn't fit the predicate, it stops evaluating.

So, if it's more likely that the condition would prove true early on it's good to use anyand vice versa.

results matching ""

    No results matching ""