Tuesday, September 16, 2008

String Contains From Array with Extension Method

Using LINQ, I wanted to find all lines in a file that didn't have any of the strings in an array of "exclude" strings that I had. This is the function that I came up with to handle that case once I'd read in the lines from the file.

        static string[] NotInSecondArray(string[] first, string[] exclude)
        {
            return first.Where(a => !a.Contains(exclude)).ToArray();
        }

However, the string Contains function doesn't take an array so you need to add something like this:

    public static class MyExtensions
    {
        public static bool Contains(this String str, string[] inArray)
        {
            foreach (string s in inArray)
            {
                if (str.Contains(s))
                {
                    return true;
                }
            }
            return false;
        }
    }

No comments:

Post a Comment