简体   繁体   English

C#数组包含部分

[英]C# Array contains partial

How to find whether a string array contains some part of string? 如何查找字符串数组是否包含字符串的某些部分? I have array like this 我有这样的数组

String[] stringArray = new [] { "abc@gmail.com", "cde@yahoo.com", "@gmail.com" };
string str = "coure06@gmail.com"

if (stringArray.Any(x => x.Contains(str)))
{
    //this if condition is never true
}

i want to run this if block when str contains a string thats completely or part of any of array's Item. 我想在块中包含一个字符串完全或任何数组的Item的一部分时运行此块。

Assuming you've got LINQ available: 假设你有LINQ可用:

bool partialMatch = stringArray.Any(x => str.Contains(x)); 

Even without LINQ it's easy: 即使没有LINQ也很容易:

bool partialMatch = Array.Exists(stringArray, x => str.Contains(x));

or using C# 2: 或使用C#2:

bool partialMatch = Array.Exists(stringArray,
      delegate(string x) { return str.Contains(x)); });

If you're using C# 1 then you probably have to do it the hard way :) 如果你正在使用C#1那么你可能必须这么做:)

If you're looking for if a particular string in your array contains just "@gmail.com" instead of "abc@gmail.com" you have a couple of options. 如果您正在查找数组中的特定字符串是否只包含“@ gmail.com”而不是“abc@gmail.com”,那么您有两个选项。

On the input side, there are a variety of questions here on SO which will point you in the direction you need to go to validate that your input is a valid email address. 在输入端,这里有各种各样的问题,这些问题将指导您确定输入是有效的电子邮件地址所需的方向。

If you can only check on the back end, I'd do something like: 如果你只能检查后端,我会做类似的事情:

emailStr = "@gmail.com";
if(str.Contains(emailStr) && str.length == emailStr.length)
{
  //your processing here
}

You can also use Regex matching, but I'm not nearly familiar enough with that to tell you what pattern you'd need. 您也可以使用正则表达式匹配,但我对此并不熟悉,告诉您需要什么样的模式。

If you're looking for just anything containing "@gmail.com", Jon's answer is your best bets. 如果您正在寻找包含“@ gmail.com”的任何内容,Jon的回答是您最好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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