Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if any value from Array1 Contains any value from Array2

How can I check if a value from an Array Contains any value from an other Array ?

For example:

string[] array1 = {"1726KB12","271","MB192"}
string[] array2 = {"KB","L1","C9"}

Those are the two arrays i’m using. I need to check if any value from array2 is contained in array1 (in this case, "KB" from array2 is contained in array1 but is not identical).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to catch this?

Every other solutions that i could find only check if both values are identical.

>Solution :

You can use LINQ’s .Any() function to return a boolean value indicating that array1 contains any value that is present in array2:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] array1 = {"1726KB12", "271", "MB192"};
        string[] array2 = {"KB", "L1", "C9"};

        bool containsValue = array1.Any(a1 => array2.Any(a2 => a1.Contains(a2)));

        if (containsValue)
        {
            Console.WriteLine("At least one value from array2 is contained within array1.");
        }
        else
        {
            Console.WriteLine("No value from array2 is contained within array1.");
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading