简体   繁体   English

C#如果包含/等于

[英]C# if contains/equals

So I'm wondering what would be the correct approach to checking a response,所以我想知道检查回复的正确方法是什么,

Example -例子 -

response = "43";

then if I use那么如果我使用

if(response.Contains("4")) {
    //do code
}

if(response.Contains("3")) {
    //do code
}

both would be equally true, therefore both executing a function, however I want it to be equal to start and end of string, so I'm using -两者都是一样的,因此两者都执行一个函数,但是我希望它等于字符串的开头和结尾,所以我正在使用 -

if(response.Equals("3")) {
   //do code
} 

therefore the above function would only execute if it WAS EQUAL TO 3 not containing 3?因此上面的函数只有在它等于 3 不包含 3 时才会执行? ( Please correct me if I'm wrong ) (如果我错了,请纠正我)

However for one statement I want to check for multiple strings/integers.但是,对于一个语句,我想检查多个字符串/整数。 So it would be more efficient for my if statement to check each item in a list, rather than repeat所以我的 if 语句检查列表中的每个项目会更有效率,而不是重复

response.Equals(".") && response.Equals(".") etc etc

how could do I do this?我怎么能这样做?

So check if response is equal to any item in所以检查响应是否等于任何项目

 List<string> mylist = new List<string>(new string[] { "1", "2", "3" });

preferably without a for loop..最好没有 for 循环..

You'l want to use mylist.Contains(response) to check for this.您需要使用mylist.Contains(response)来检查这一点。 List.Contains checks for exact matches only, so it will avoid your original issue of having two blocks execute. List.Contains 仅检查完全匹配,因此它将避免您执行两个块的原始问题。

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

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