Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple string comparison with C#

Tags:

string

c#

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?

ADDED

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");         }     } } 
like image 693
prosseek Avatar asked May 17 '11 17:05

prosseek


People also ask

Can I use == to compare strings in C?

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.

How do you compare strings in C?

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

How do you check if one string is greater than another in C?

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.


2 Answers

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 } 
like image 115
jason Avatar answered Oct 04 '22 05:10

jason


if ((new[]{"A","B","C"}).Contains(x, StringComparer.OrdinalIgnoreCase)) 
like image 23
adrianm Avatar answered Oct 04 '22 05:10

adrianm