Alex Ramos
Alex Ramos

Reputation: 23

Linq Check if array of string has a partial match in other array

I want to return a string of matches found in the array1

public static string[] FindMatchs(string[] array1, string[] array2) {
    return array1.Where(x => array2.Contains(x)).ToArray();
}

input:

var a1 = new string[] { "ca", "tr", "stack" };
var a2 = new string[] { "car", "house", "tree", "stackoverflow", "bus" };

the method should return "ca", "tr", "stack"

Upvotes: 2

Views: 1633

Answers (3)

Sateesh Pagolu
Sateesh Pagolu

Reputation: 9606

You are almost there.. a slight change to the line in you method.

return array1.Where(x => array2.Any(y=>y.Contains(x))).ToArray();

Upvotes: 1

Joakim Hansson
Joakim Hansson

Reputation: 544

I made a mistake in my previous code. Please see below for a working example.

You want to use a combination of .Contains() and .Any() to achieve what you are looking for.

Here is a code example based on your code, that should work (names in signature has been changed for clarity):

public static string[] FindMatchs(string[] array, string[] filter) {
    return array.Where(x => filter.Any(y => x.Contains(y))).ToArray();
}

Here is a live example of it: https://dotnetfiddle.net/HdB79V

Upvotes: 2

tam tam
tam tam

Reputation: 1900

The following example returns matches in two lists:

public class names
{
  public int ID {get;set;}
  public string Name {get;set;}
}

List<names> l1 = new List<names>();
List<names> l2 = new List<names>();

Populate both list:

for example

   Name xyz = new Name()
    xyz.id = 1;
    xyz.name = "blah";
    l1.Add(xyz)

var matches = (from l1 in list1
        join l2 in list2 on l1.Name equals l2.Name
        select sp).ToList();

OR if you want to use Arrays only

var list1 = new string[] {"xyz", "abc"};
var list2 = new string[] {"abc"};
var matches = list1.Intersect(list2);
foreach (string s in matches)
{
 //s will return common 

}

Upvotes: 0

Related Questions