Special Offer: My C#/.NET Bootcamp Course is out now. Get 10% OFF using the code FRIENDS10.

Recently I came around the following tricky bits of code.

if (myList.All(myString.Contains))

It took me several seconds to figure out what’s exactly going on in there. Especially if the initialization part of the code is not near the line in question, it’ll get confusing very quickly.
To be fair I’ll provide you with an full code example below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StringContains
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = @"Hello John!, Hello Alex!, 
                                Hello Bob!, Hello Tim!";

            var myList = new List<string>();
            myList.Add("Hello John!");
            myList.Add("Hello Alex!");
            myList.Add("Hello Bob!");
            myList.Add("Hello Tim!");

            if (myList.All(myString.Contains))
            {
                Debug.WriteLine(@"myString contains all 
                                    strings from myList");
            }
            else
            {
                Debug.WriteLine(@"myString does not contain all 
                                    strings from myList");
            }
        }
    }
}

What’s going on in this code?

Line 22 checks whether myString contains all elements from the myList list.

In my opinion this code is not very easy understandable. So I wanted to improve the code in question. I like the short code which really does the work. Therefore I decided to keep the line. What I wanted to improve was the readability of the code. Because of that I created an extension method specific to List<string>.

    public static class StringListExtension
    {
        public static bool AllElementsContainedIn(
            this List<string> list, string str)
        {
            return list.All(str.Contains);
        }
    }

In my opinion this code looks much clearer. In addition it can be used throughout the entire code base which makes it a very powerful extension method.

string myString = @"Hello John!, Hello Alex!, 
                    Hello Bob!, Hello Tim!";

var myList = new List<string>();
myList.Add("Hello John!");
myList.Add("Hello Alex!");
myList.Add("Hello Bob!");
myList.Add("Hello Tim!");

if (myList.AllElementsContainedIn(myString))
{
    Debug.WriteLine(@"myString contains all 
                        strings from myList");
}
else
{
    Debug.WriteLine(@"myString does not contain all 
                        strings from myList");
}

What’s your opinion?

StringContains full example code

Claudio Bernasconi

I'm an enthusiastic Software Engineer with a passion for teaching .NET development on YouTube, writing articles about my journey on my blog, and making people smile.