public static bool isExactLocation(string item)
{
Boolean isLocation = false;
String[] LocationcheckList = File.ReadAllLines(@"C:\list\LocationCheckList");
List<string> LocationList = new List<string>();
foreach (String words in LocationcheckList)
{
String Words = words.ToLower().Trim();
LocationList.Add(Words);
}
String input = item.ToLower().Trim();
foreach (string value in LocationList)
{
if (input.Equals(value))
{
isLocation = true;
break;
}
}
return isLocation;
}
我的位置列表具有以下值:
Saudi
Arabia
Tokyo
India
Germany
我的问题是,当我作为沙特阿拉伯进行输入时,它应该获取输入中的每个单词,并与位置列表进行比较,如果列表中存在该单词,它应该给出 true,并且也只使用 equals 方法。请帮忙。
首先,让我们读取文件一次:
using System.Linq;
...
// HashSet.Contains is faster then List.Contains: O(1) vs. V(N)
private static HashSet<string> s_Words = new HashSet<string>(File
.ReadLines(@"C:\list\LocationCheckList")
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(item => item.Trim()),
StringComparer.OrdinalIgnoreCase
);
然后您可以轻松检查:
public static bool isExactLocation(string item) {
return item
?.Split(' ', StringSplitOptions.RemoveEmptyEntries)
?.All(word => s_Words.Contains(word)) ?? null;
}
编辑:如果您坚持
List<strint>
和for
(foreach
)循环:
private static List<string> s_Words = File
.ReadLines(@"C:\list\LocationCheckList")
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(item => item.Trim())
.ToList();
然后我们可以循环...
public static bool isExactLocation(string item) {
if (null == item)
return false;
string[] words = item
.Split(' ', StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words) {
bool found = false;
foreach (string location in s_Words) {
if (location.Equals(word, StringComparison.OrdinalIgnoreCase)) {
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
你可以做类似的事情
使用 System.Linq; LocationCheckList.Any(x=> item.Split(' ').Contains(x))
但要留意“韩国 vs 南非”