[英]test if string value is contained in array of strings
Hi I have a list of words which i am looking for if this word is found i want the valuye removed from my array嗨,我有一个单词列表,如果找到该单词,我要查找该单词,我希望从数组中删除该值
private static string[] WordList = { "Example No", "Name", "Client ID"};
var listToTest = new[] { "ME 0.3", "Example No.: 1243", "Name.:"};
var newList= new List<string>();
foreach (var value in listToTest)
{
if (!WordList.Any(x => x.Contains(value)))
{
newList.Add(value);
}
}
return newList.ToArray();
my test returns all the value where I only want it to return "ME 0.3"我的测试返回我只希望它返回“ME 0.3”的所有值
.WordList.Any(x => x.Contains(value))
will return true
if no element in WordList
contains value
and false
if there is at least one element in WordList
that contains value
.如果 WordList 中没有元素包含
value
, .WordList.Any(x => x.Contains(value))
将返回true
,如果WordList
中至少有一个元素包含value
,则WordList
false
。
So your code will return an array of elements of listToTest
, that no element in WordList
contains them, but as you said you want an array of elements of listToTest
that they contain no element of WordList
.因此,您的代码将返回 listToTest 的元素数组,
listToTest
中的任何元素WordList
包含它们,但是正如您所说,您想要listToTest
的元素数组,它们不包含WordList
的元素。 So in ... x.Contains(value)))
replace x
and value
with each other:所以在
... x.Contains(value)))
中,将x
和value
相互替换:
private static string[] WordList = { "Example No", "Name", "Client ID"};
var listToTest = new[] { "ME 0.3", "Example No.: 1243", "Name.:"};
var newList= new List<string>();
foreach (var value in listToTest)
{
if (!WordList.Any(x => value.Contains(x)))
{
newList.Add(value);
}
}
return newList.ToArray();
By the way there is a neater way:顺便说一句,有一个更整洁的方法:
var result = listToTest.Where(x => !WordList.Any(y => x.Contains(y))).ToArray();
// Usage:
foreach (var s in result)
Console.WriteLine(s);
// Output:
// ME 0.3
Description:描述:
Enumerable.Where
Method: Filters a sequence of values based on a predicate. Enumerable.Where
方法:根据谓词过滤一系列值。Enumerable.Any
Method: Determines whether any element of a sequence exists or satisfies a condition. Enumerable.Any
方法:确定序列的任何元素是否存在或是否满足条件。Enumerable.ToArray
Method: Creates an array from a IEnumerable. Enumerable.ToArray
方法:从 IEnumerable 创建一个数组。String.Contains(String)
Method: Returns a value indicating whether a specified substring occurs within this string. String.Contains(String)
方法:返回一个值,该值指示指定的 substring 是否出现在此字符串中。Not the most efficient, but works.不是最有效的,但有效。
newList = listToTest.Where((x) =>
{
return WordList.Where(x2 => x.IndexOf(x2) != -1).Count() == 0;
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.