2

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"

0

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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 

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.