logo

C# How to search a Generic List using Find and FindAll with a lambda expression

Overview: In this code snippet, I demonstrate how to create a list using a struct and how too use an enumeration type called GenderType in the struct. A list of Person struct type is created and a lambda function is created as the predicate of the Find extension and the FindAll extension. The Find extension searches the list until the first record with a match is encounter then stops. The FindAll extension searches the list for all matches returning true.
 
       enum GenderType { Male, Female}

        struct Person {
            public int Id;
            public string Name;
            public int Age;
            public GenderType Gender;
       }
        [TestMethod]
        public void TestFindOnList()
        {
            List<Person> list = new List<Person>() {
                new Person() {Id=1, Name="Bob Jones",Age=31,Gender=GenderType.Male },
                new Person() {Id=2,Name="Dan Smith",Age=40,Gender=GenderType.Male },
                new Person() {Id=3, Name="Susan Bright", Age=44,Gender=GenderType.Female },
                new Person() {Id=4, Name="Jimmy Davis", Age=50,Gender=GenderType.Female }
            };
            Person person = list.Find((Person p) => p.Id == 1);
            Assert.AreEqual(person.Name , "Bob Jones");

            List<Person> matches = null;

            matches = list.FindAll (p => p.Gender == GenderType.Female);

            foreach (var item in matches)
            {
                Console.WriteLine($"Name: {item.Name}\t Gender: {item.Gender}");
            }
            Assert.IsTrue(matches.Count>0);
 
        }

Predicate Lambda Function Rules

1. Lambda expression take parameters (Person p). If no parameter are given then use ()=>{} indicating an empty parameter list.

2. The Lambda parameters can be passed by reference (ref int x)=>{x++}. The x increment is permanent.

3. The Lambda expression body can be made of multiple statements, variable assignments, or method calls. The lambda expression can modify class variables external to the expression, be careful.

s