How to check if a string matches all of these?

Trying to rewrite this with LINQ:

if (mode != "A" && mode != "B" && mode != "C" && mode != "D" && mode != "E" && mode != "F" && mode != "G") { continue; } 

What will be the most clear and concise way to reorganize this? I could have sworn I saw such a post before, but I cannot find it at the moment.

+4
source share
5 answers

You can use the Contains method IList<T> :

 IList<string> modes = new[]{"A","B","C","D","E","F","G"}; if (!modes.Contains(mode))... 
+10
source

Write an extension method for a string class

 public static bool In(this string s, params string[] values) { return values.Any(x => x.Equals(s)); } 

name it that way

 if (!mode.In("A", "B", "C", "D","E","F", "G") { continue; } 
+2
source
 var modes = new[] { "A","B","C","D","E","F","G"}; if (modes.All(a => mode != a)) continue; 
+1
source

I use this extension method all the time

 public static bool IsIn(this string source, params string[] parms) { return parms.Contains(source); } 

And use it as follows:

 if (!mode.IsIn("A", "B", "C", "D", "E", "F", "G")) { continue; } 

The next step, if you use it a lot,

 public static bool IsNotIn(this string source, params string[] parms) { return !IsIn(source, params); } 

and you get a little more readable

 if (mode.IsNotIn("A", "B", "C", "D", "E", "F", "G")) { continue; } 
+1
source
 string s = "ABCDEFG"; bool res = s.Any(item => { return (int)item > 64 && (int)item < 72; }); 
+1
source

Source: https://habr.com/ru/post/1443676/


All Articles