Reputation:
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.
Upvotes: 0
Views: 489
Reputation: 27927
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;
}
);
Upvotes: 1
Reputation: 186678
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)));
Upvotes: 1
Reputation: 204
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));
Upvotes: 1