The Quantifiers operators

            1. What is the Any operator?

            2. What is the signature of the Any operator?

            3. What is the All operator?

            4. What is the signature of the All operator?

            5. What is the Contains operator?

            6. What is the signature of the Contains operator?

            We can use the Quantifiers operators when we need to check whether elements belong to a sequence.

The Any operator returns true if a given sequence contains any elements which satisfy a given condition.

 

public static bool Any<TSource>(

    this IEnumerable<TSource> source);

 

public static bool Any<TSource>(

    this IEnumerable<TSource> source,

    Func<TSource, bool> predicate);

 

Example 1:

 

            Trace.WriteLine((from c in Data.Customers

                             select c.Name).Any(c => c == "Marco"));

Output:

True

 

The All operator returns true if the all elements of a given sequence satisfy a given condition.

Example 2:

 

            Trace.WriteLine((from c in Data.Customers

                             from o in c.Orders

                             select o).All( o => o.Shipped ));

Output:

True

 

Note: For an empty sequence the All operator always returns true.

 

Example 3:

 

Trace.WriteLine(Enumerable.Empty<Order>().All(o => o.Shipped));

 

Output:

True

 

The Contains operator returns true if a given sequence contains an element which is given as a parameter.

Example 4:

 

            Trace.WriteLine((from p in Data.Products

                             select p.Price).Contains(10));

Output:

True

 

Example 5:

 

            Trace.WriteLine((from p in Data.Products

                             select p).Contains(new Product { IdProduct = 1, Price = 10 }, new ProductComparer()));

 

Output:

True

 

Note: By default the Conatins operator uses a standart comparer. To avoid mistakes is better to define a special comparer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s