匹配 List中的部分字符串在另一个列表中
这就是我。我得到以下代码:
foreach (var str in usedCSS) {
if (CSS.Any(c => c.IndexOf(str)>0))
Response.Write(str + "<br />");
else
Response.Write("Could not find: " + str + "<br />");
}
usedCSS
= List
CSS
= List
但是,我需要反之亦然...
我希望 var str inusedCSS
为 var str in CSS
usedCSS
仅包含 css 名称的字符串例如:.header
CSS
包含实际 css 的字符串,例如: .header {font-size:14px;}
基本上,我需要的是打印出使用的实际 CSS。 我目前的代码恰恰相反,它只返回 css 名称, 不是实际的CSS。
its me. i got the following code:
foreach (var str in usedCSS) {
if (CSS.Any(c => c.IndexOf(str)>0))
Response.Write(str + "<br />");
else
Response.Write("Could not find: " + str + "<br />");
}
usedCSS
= List<string>
CSS
= List<string>
but, i need it the other way around...
i want the var str in usedCSS
to be var str in CSS
usedCSS
contains strings of only the css names e.g: .header
CSS
contains string of the actual css e.g: .header {font-size:14px;}
basicly, what i need is to print out the actuall CSS that is used.
The code i currently have does the exact opposite, it returns only the css names,
not the actuall css.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我明白你想要正确做什么,你就可以这样做。
FirstOrDefault()
查找谓词匹配的第一个匹配项并返回它,如果未找到,则返回null
(string
类型的默认值)。然后我们需要的只是StartsWith()
字符串方法,将 CSS 中的每个项目按前缀与相关的str
进行匹配。ps 如果您只期望一个匹配或没有匹配,如果您可以有多个匹配,并且想要全部匹配,则上述方法有效:
If I understand what it is you're trying to do correctly, you could do this.
FirstOrDefault()
finds the first occurrence of a predicate match and returns it, ornull
(default for typestring
) if not found. Then all we need is theStartsWith()
string method to match each item in CSS prefix-wise with thestr
in question.p.s. The above works if you only expect one or no matches, if you can have multiple matches, and want them all:
尝试
Try
以及相反的
示例代码...
结果:
或
结果:
and the reverse
Sample code...
result:
or
result:
这是更多“存档”的解决方案:
您可以使用以下测试代码进行检查:
请注意,此类代码无法区分
'.foo'
和'.foobar'
。一般情况下,如果它计量,您应该使用正则表达式进行更复杂的检查。Here is more "archived" solution:
You can check, using this test code:
Pay attention, that such code could not distinguish
'.foo'
from'.foobar'
. In general case if it meters you should use more complicated check with regular expressions.