Linq检查字符串数组是否在其他数组中部分匹配 [英] Linq Check if array of string has a partial match in other array
本文介绍了Linq检查字符串数组是否在其他数组中部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想返回在array1中找到的匹配字符串
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();
}
输入:
var a1 = new string[] { "ca", "tr", "stack" };
var a2 = new string[] { "car", "house", "tree", "stackoverflow", "bus" };
该方法应返回"ca","tr",堆栈"
the method should return "ca", "tr", "stack"
推荐答案
我在先前的代码中犯了一个错误. 请参见下面的工作示例.
I made a mistake in my previous code. Please see below for a working example.
您要结合使用.Contains()和.Any()来实现所需的功能.
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();
}
这是一个生动的例子: https://dotnetfiddle.net/HdB79V
Here is a live example of it: https://dotnetfiddle.net/HdB79V
这篇关于Linq检查字符串数组是否在其他数组中部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文