Home > Development > LINQ Any and All Operators

LINQ Any and All Operators


Just a quickie. This will show you how to use these operators to determine if items in a collection meet a predicate. Here we go.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqOperators
{

    public class Customer
    {

        public Customer(int id, string name)
        {
            Id = id;
            Name = name;
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public static IList<Customer> GetCustomers()
        {
            return new List<Customer>
                       {
                           new Customer(1, "Blair"),
                           new Customer(2, "Tim"),
                           new Customer(3, "Tom"),
                           new Customer(4, "Eddie"),
                           new Customer(5, "Sunny")
                       };
        }
    }

    class Program
    {
        static void Main()
        {

            //Testing if we have any elements in the collection
            Console.WriteLine("Do we have any elements in the collection: {0}",Customer.GetCustomers().Any());

            //Testing if we have any elements in the collection satisfying the predicate
            Console.WriteLine("Do we have any elements in the collection satisfying the predicate: {0}", Customer.GetCustomers().Any(x => x.Id > 2));

            //Testing if we have all elements in the collection satisfying the predicate
            Console.WriteLine("Do we have all elements in the collection satisfying the predicate: {0}", Customer.GetCustomers().All(x => x.Name.Length > 0));


            Console.ReadKey();
        }
    }
}

Blair….

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: