0

There are similar questions out there on how to check if a string contains any inputs on a list, but I am confused on how to do this for two list of strings.

Suppose I have a first List containing:

["five", "four", "three", "two", "one"]

and have a second List<string> containing:

["bathroom", "twelve", "thirteen", "fou"]

I want to see if any of the "substrings" within List 2 match with List 1. If any of the substrings in List 2 are found in List 1 (i.e. "fou") it is true, otherwise if there are no substring matches found it is false.

I'd imagine this would use linq but I am unsure how to do this for two string lists.

1
  • It would help to put a tag or mention in your question the language that you are using. Commented Feb 20, 2021 at 0:51

3 Answers 3

1
var result = list1.Any(s1 => list2.Any(s2 => s1.Contains(s2)));

or, using more tricky syntax

var result = list1.Any(s1 => list2.Any(s1.Contains));
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to have just bool result - if any string (say, "fou") within secondList contains in any item within firstList (say, four: four) - you can try

  List<string> firstList = new List<string>() {
    "five", "four", "three", "two", "one",
  };

  List<string> secondList = new List<string>() {
    "bathroom", "twelve", "thirteen", "fou",
  };  

  ...

  bool result = secondList
    .Any(second => firstList.Any(first => first.Contains(second))); 

Comments

1
var list1 = new List<string> { "five", "four", "three", "two", "one" };
var list2 = new List<string> { "bathroom", "twelve", "thirteen", "fou" };
var found = list1.Any(i1 => list2.Any(i2 => i1.Contains(i2)));

EDIT

Based on your comments, I understand that you are having trouble debugging. You can extend the above code like for example below, so it helps you better understand what the code is doing:

var list1 = new List<string> { "five", "four", "three", "two", "one" };
var list2 = new List<string> {  "f", "o", "t" };
var found = list1.All(i1 =>
    { 
        var l1Result = list2.Any(i2 => 
            {
                var l2Reuslt = i1.Contains(i2);
                Console.WriteLine($"{i1} constains {i2}: {l2Reuslt}");
                return l2Reuslt;
            });
        Console.WriteLine($"{i1} Final : {l1Result}");
        return l1Result;
    }
);

4 Comments

If you were to use All instead, would you just replace?
@Berek i don't understand your question.
@Berek try it out yourself? ;-)
If you replace both any with All then it means that all of list 1 needs to have all of list 2 containing. if you do list1.All / list2.Any means all of list1 needs at least one matching item in list 2...

Your Answer

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