Finding Items Using Predicates in Generic List C#

using System; 
using System.Collections.Generic; 
 
namespace w3predicates { 
    class Listw3predicates { 
 
        static void Main(string[] args) { 
 
            // create the list collection 
            List<string> list = new List<string>() { 
                "A", "B", "C", "D",  
                 "E", "F", "G"}; 
 
            // create a predicate that uses the  
            // PredicateExample method 
            Predicate<string> p = new Predicate<string>(PredicateExample) ; 
 
            // use the Exists method with the predicate 
            bool result1 = list.Exists(p) ; 
 
            // use the Exists method with a lambda expression 
 
            bool result2 = list.Exists(s => s.Length == 1 && s[ 0] == 'B' ) ; 
 
            // write out the results 
            Console.WriteLine("Result1: {0}, Result2: {1}", result1, result2) ; 
 
            // wait for input before exiting 
            Console.WriteLine("Press enter to finish"); 
            Console.ReadLine(); 
        } 
 
        static bool PredicateExample(string str) { 
            return str.Length ==  && str[0] == 'B' ; 
        } 
    } 
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.