简体   繁体   English

测试字符串值是否包含在字符串数组中

[英]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)))中,将xvalue相互替换:

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:描述:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM