C# - Test for Equality Among Several Strings

  • Thread starter Thread starter dwohlfahrt
  • Start date Start date
D

dwohlfahrt

Hi All,

I've spent the last few hours looking for a simple yet clean method via
C# that will allow me to test whether three or more strings are equal
(by value, of course).

I've been forced to go with the obvious (but ugly, if you ask me)
method below:

string a = "test";
string b = "test";
string c = "test";
string d = "test";

if ((a == b) && (b == c) && (c == d))
{
// do something here
}

I'd simply like to be able to do something like this...

if (a == b == c == d)
{
// do something here
}

I'm aware that the order of operations with boolean operators won't
allow for the above statement, resulting in an invalid boolean-string
comparison at run-time.

Also, I don't want to go the route of putting these four strings into a
sorted array or a hash table as an alternate solution to this problem,
which are the only other solutions I've seen mentioned thus far. Those
two options are just plain overkill if you ask me... at least in my
case.

Does it not seem like there should be a more clever mechanism available
by which to handle this? Now I know I can write (or override) my own
function to handle this, but my mind keeps telling me there's a better,
smarter way about it. So... any ideas?

Also, I'd love to here if anyone out there knows of another language
(possibly Ruby?) that could perform a task like this with much more
style and ease. I'm definitely looking for a language that can offer
me more flexibility than C#.

Thanks a bunch!
Derek
 
How about this? copes with any number and any type, optionally
allowing your own comparer (definition of equality)...

Marc

static void Main()
{
Console.WriteLine(AllEqual("abc", "abc", "abc"));
Console.WriteLine(AllEqual("abc", "def", "abc"));
Console.WriteLine(AllEqual(1, 1, 1, 1, 1));
Console.WriteLine(AllEqual(1, 2, 3, 2, 1));
}

static bool AllEqual<T>(params T[] values)
{
return AllEqual<T>(EqualityComparer<T>.Default, values);
}
static bool AllEqual<T>(IEqualityComparer<T> comparer, params T[]
values)
{
if(values==null) throw new ArgumentNullException("values");
if (comparer == null) throw new
ArgumentNullException("comparer");
int len = values.Length;
if(len<2) throw new InvalidOperationException("2 or more
values required");

T val = values[0];
for (int i = 1; i < len; i++)
{
if (!comparer.Equals(val, values))
{
return false;
}
}
return true;
}
 
A simple example:

static bool Equals(params string[] values)
{
for (int i = 1; i < values.Length; i++)
{
if (values[0] != values) return false;
}
return true;
}
 
Hi,

Hi All,

I've spent the last few hours looking for a simple yet clean method via
C# that will allow me to test whether three or more strings are equal
(by value, of course).

I've been forced to go with the obvious (but ugly, if you ask me)
method below:

Unless you have your values in a collection I do not see a better way
 
Back
Top