要检查一个字符串包含一个元素从(字符串)列表 - 有没有更好的方式来写这个code? [英] To check if a string contains an element from a list (of strings) - Is there a better way to write this code?

查看:128
本文介绍了要检查一个字符串包含一个元素从(字符串)列表 - 有没有更好的方式来写这个code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关code以下块:

        For I = 0 To listOfStrings.Count - 1
            If myString.Contains(lstOfStrings.Item(I)) Then
                Return True
            End If
        Next
        Return False

输出是:

案例1:

的myString:C:\\文件\\ myfile.doc

myString: C:\Files\myfile.doc

listOfString:C:\\文件\\,C:\\ Files2 \\

listOfString: C:\Files\, C:\Files2\

结果:真

案例2:

的myString:C:\\ Files3 \\ myfile.doc

myString: C:\Files3\myfile.doc

listOfString:C:\\文件\\,C:\\ Files2 \\

listOfString: C:\Files\, C:\Files2\

结果:假

目前的任何时间列表(listOfStrings)可含有多个项目(最小20),它具有针对数千字符串(像的myString)的情况进行检查。

At any time the list (listOfStrings) may contain several items (minimum 20) and it has to be checked against a thousands of strings (like myString).

有没有更好的(更有效)的方式来写这个code?

Is there a better (more efficient) way to write this code?

推荐答案

使用LINQ,并使用C#(我不知道VB多少这些天):

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

或(更短,更高效,但可以说不太清楚):

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

如果您在测试平等,这将是值得看的 HashSet的等,但是这不会与部分匹配帮助,除非你把它分解成片段,并添加订单的复杂度。

If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.


更新:如果你真的意味着StartsWith,那么你可以对列表进行排序,并将其放置到一个数组;然后用 Array.BinarySearch 找到每一个项目 - 通过查找检查,看它是否是全部或部分比赛

update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

这篇关于要检查一个字符串包含一个元素从(字符串)列表 - 有没有更好的方式来写这个code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆