LINQ in C# - Non-Deferred Operator Examples- Any/All/Contains - Quntifiers

Any

The Any operator returns true if any one element of an input sequence matches a condition.

Any - Type 1 - without condition - Example

  • Any without conditions, but a source sequence with at least with a single element. will return true
  string[] names = {"Name1", "Name2", "Name3", "Name4" };

            bool found = names.Any();

            Console.WriteLine(found);
//Output
True
  • Any without conditions, with a source sequence with zero element will return false.
string[] names = {};

            bool found = names.Any();

            Console.WriteLine(found);
 //Output
false

Any - Type 2 - with condition - Example

string[] names = {"Ramkumar", "Rajesh", "Manikandan", "Ram" };

            bool ThreeLetterNamefound = names.Any(x=> x.Length==3);
            Console.WriteLine(ThreeLetterNamefound); //True

            bool FourLetterNamefound = names.Any(x => x.Length == 4);
            Console.WriteLine(FourLetterNamefound); //False

All

The All operator returns true if every element in the input sequence matches a condition.
All needs to have at least one condition, it is mandatory 

string[] names = {"Arun", "Raja" };

            bool ThreeLetterNamefound = names.All(x=> x.Length == 4);
            Console.WriteLine(ThreeLetterNamefound); //True
 //Output
True 

Contains

The Contains operator returns true if any element in the input sequence matches the specified value.

Contains - Type 1 - Example 1

string[] names = {"Arun", "Raja", "Ramkumar", "RaviRajan" };

            bool Namefound = names.Contains("Raja");
            Console.WriteLine(Namefound); //True

Contains - Type 2 with Custom Comparer - Example 1

Implementation of IEqualityComparer, just for shown here for show how IEqualityComparer works


class StringComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            //throw new NotImplementedException();
            return x.Length == y.Length;
        }

        public int GetHashCode(string obj)
        {
            //throw new NotImplementedException();
            return obj.GetHashCode();
        }
    }

 string[] names = {"Arun", "Raja", "Ramkumar", "RaviRajan" };

            bool Namefound = names.Contains("abcd", new StringComparer());
            Console.WriteLine(Namefound); //True

            bool NamefoundFalse = names.Contains("abc", new StringComparer());
            Console.WriteLine(Namefound); //False becuase there is no element with 3 letters

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...