Let's say I need to compare if string x is "A", "B", or "C".
With Python, I can use in operator to check this easily.
if x in ["A","B","C"]: do something
With C#, I can do
if (String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) || ...) do something
Can it be something more similar to Python?
I needed to add System.Linq
in order to use case insensitive Contain().
using System; using System.Linq; using System.Collections.Generic; class Hello { public static void Main() { var x = "A"; var strings = new List<string> {"a", "B", "C"}; if (strings.Contains(x, StringComparer.OrdinalIgnoreCase)) { Console.WriteLine("hello"); } } }
or
using System; using System.Linq; using System.Collections.Generic; static class Hello { public static bool In(this string source, params string[] list) { if (null == source) throw new ArgumentNullException("source"); return list.Contains(source, StringComparer.OrdinalIgnoreCase); } public static void Main() { string x = "A"; if (x.In("a", "B", "C")) { Console.WriteLine("hello"); } } }
Because C strings are array of characters. Arrays are simply pointers to the first element in the array, and when you compare two pointers using == it compares the memory address they point to, not the values that they point to.
The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
Use Enumerable.Contains<T>
which is an extension method on IEnumerable<T>
:
var strings = new List<string> { "A", "B", "C" }; string x = // some string bool contains = strings.Contains(x, StringComparer.OrdinalIgnoreCase); if(contains) { // do something }
if ((new[]{"A","B","C"}).Contains(x, StringComparer.OrdinalIgnoreCase))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With