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"
.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
.
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
. So in ... x.Contains(value)))
replace x
and value
with each other:
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.Any
Method: Determines whether any element of a sequence exists or satisfies a condition. Enumerable.ToArray
Method: Creates an array from a IEnumerable. String.Contains(String)
Method: Returns a value indicating whether a specified substring occurs within this string. Not the most efficient, but works.
newList = listToTest.Where((x) =>
{
return WordList.Where(x2 => x.IndexOf(x2) != -1).Count() == 0;
}).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.