ContainsAny

CSharp · Console

/Program.cs

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

public class Program
{
	public static void Main()
	{
		var tags = new [] {"a","b","c"};
		var search = new [] {"b"};
		
		var isMatch1 = tags.Any(x => search.Contains(x));
		var isMatch2 = tags.Intersect(search).Any();
		var isMatch3 = tags.ContainsAny(search);
		
		Console.WriteLine(isMatch1);
		Console.WriteLine(isMatch2);
		Console.WriteLine(isMatch3);
		
		var str = "hello world";
		var words = new [] {"world", "earth", "terra"};
		
		var contains1 = words.Any(w => str.Contains(w));
		var contains2 = str.ContainsAny(words);
		
		Console.WriteLine(contains1);
		Console.WriteLine(contains2);
	}
}


public static class StringExtensions
{
    /// <summary>
    /// Tests whether any of the entries in the search list can be found in the source string
    /// </summary>
    public static bool ContainsAny(this string source, IEnumerable<string> search)
    {
        return search.Any(source.Contains);
    }
}

public static class LinqExtensions
{
    /// <summary>
    /// Tests whether the source list matches any of the values in the search list
    /// </summary>
    public static bool ContainsAny<T>(this IEnumerable<T> source, IEnumerable<T> search)
    {
        return source.Any(search.Contains);
    }
}
;