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

Share this

Claudio Bernasconi

Claudio Bernasconi is a professional software developer, Microsoft certified technology specialist, blogger, technology enthusiast and founder of CarParking Schweiz. Since 2010 he works for KMS AG in Lucerne, Switzerland.