C#: Check If List Contains Element That Contains A String And Get That Element

To check if a list contains an element that contains a specific string and retrieve that element, you can use the Any method with a lambda expression and the FirstOrDefault method. Here’s an example:

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

class Program
{
    static void Main()
    {
        // Example list
        List<string> fruits = new List<string> { "apple", "banana", "kiwi", "orange", "mango" };

        // String to search for
        string searchString = "an";

        // Check if any element contains the search string and retrieve that element
        string result = fruits.FirstOrDefault(fruit => fruit.Contains(searchString));

        // Print the result
        if (result != null)
            Console.WriteLine("Found: " + result);
        else
            Console.WriteLine("No match found.");
    }
}

In this example, the lambda expression in the FirstOrDefault method checks each element in the list to see if it contains the search string. If a match is found, the first matching element is returned. If no match is found, null is returned.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!