简体   繁体   English

C# 字符串数组包含来自另一个字符串数组的字符串部分

[英]C# Array of strings contains string part from another array of strings

Is there a way using LINQ, to find if string from one array of strings contains (partial) string from another array of strings?有没有办法使用 LINQ 来查找一个字符串数组中的字符串是否包含另一个字符串数组中的(部分)字符串? Something like this:像这样的东西:

string[] fullStrings = { "full_xxx_part_name", "full_ccc_part_name", "full_zzz_part_name" };
string[] stringParts = { "a_part", "b_part", "c_part", "e_part" }; 

// compare fullStrings array with stringParts array
// full_ccc_part_name contains c_part (first match is OK, no need to find all)
// return index 1 (index 1 from fullStrings array)

This is asked rather for educational purpose.这是为了教育目的而提出的。 I'm aware that Linq does not magically avoid the loop, instead does it in the background.我知道 Linq 不会神奇地避免循环,而是在后台执行。

You can use Where + Any with string methods:您可以将Where + Any与字符串方法一起使用:

string[] matches = fullStrings
     .Where(s => stringParts.Any(s.Contains))
     .ToArray();

If you want to compare in a case insensitive way use IndexOf :如果您想以不区分大小写的方式进行比较,请使用IndexOf

string[] matches = fullStrings
     .Where(s => stringParts.Any(part => s.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0))
     .ToArray();

In case you want the indexes:如果您想要索引:

int[] matches = fullStrings 
     .Select((s, index) => (String: s, Index: index))
     .Where(x => stringParts.Any(x.String.Contains))
     .Select(x => x.Index)
     .ToArray();

You would of course need to use some type of loop to find the index.您当然需要使用某种类型的循环来查找索引。 Here is a solution using Linq.这是使用 Linq 的解决方案。 This will return the first index if a match is found or -1 if none is found:如果找到匹配项,这将返回第一个索引,如果没有找到匹配项,则返回 -1:

var index = fullStrings
              .Select((s,i) => (s, i))
              .Where(x => stringParts.Any(x.s.Contains))
              .Select(x => x.i)
              .DefaultIfEmpty(-1)
              .First();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM