if condition, multiple options

  • (2 Pages)
  • +
  • 1
  • 2

22 Replies - 2339 Views - Last Post: 02 March 2016 - 08:07 AM

#1 oyyou  Icon User is offline

  • D.I.C Head

Reputation: 28
  • View blog
  • Posts: 196
  • Joined: 26-April 10

if condition, multiple options

Posted 18 December 2015 - 03:57 AM

I've been programming for a few years, and something that is becoming tedious, is looking for different values, of the same variable. See below
if(myString == "Derp" || myString == "Rawr" || myString == "Blargh")
{
 // something
}



Why isn't there an easier way!? I mean, I know I can do a list
List<string> myStrings = new List<string>()
{
 "Derp",
 "Rawr",
 "Blargh",
};

if(myStrings.Contains(myString))
{
 // still something
}



But that's not what I want! I want something more like this
if(myString.Equals("Derp", "Rawr", "Blargh"))
{
 // definitely still something
}



I know I can make an extension method for strings, but this problem reaches out from more than strings, and I feel like Microsoft should have something for this. Maybe something in C# 6.0? I don't know.. Just wanted to rant, and see what others thought..

Is This A Good Question/Topic? 0
  • +

Replies To: if condition, multiple options

#2 andrewsw  Icon User is online

  • lashings of ginger beer
  • member icon

Reputation: 6337
  • View blog
  • Posts: 25,550
  • Joined: 12-December 12

Re: if condition, multiple options

Posted 18 December 2015 - 04:46 AM

If you will only need the list once then you can do this:
    if ((new string[] { "Bob", "Ted", "Fred" }).Contains("Fred")) {
        Console.WriteLine("it does");
    }

but you aren't gaining much other than reducing the character count and, some would say, reducing clarity/maintainability.

I might use this in preference to your first code block, but maybe not the second.

This post has been edited by andrewsw: 18 December 2015 - 04:50 AM

Was This Post Helpful? 0
  • +
  • -

#3 oyyou  Icon User is offline

  • D.I.C Head

Reputation: 28
  • View blog
  • Posts: 196
  • Joined: 26-April 10

Re: if condition, multiple options

Posted 18 December 2015 - 05:02 AM

Yeah, there is that, I just wish I there was something implemented already, or maybe something in the .Net framework like the below for each of the value types in C#.. But I don't know!
public static bool Equals(this string value, params string[] values)
{
 return values.Contains(value);
}


This post has been edited by andrewsw: 18 December 2015 - 05:06 AM
Reason for edit:: Removed previous quote, just press REPLY

Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5824
  • View blog
  • Posts: 19,822
  • Joined: 05-May 12

Re: if condition, multiple options

Posted 18 December 2015 - 06:16 AM

To me, this method fits more naturally with a collection rather than a base type. So the .NET framework designers got it right.
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is online

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6504
  • View blog
  • Posts: 14,355
  • Joined: 02-June 10

Re: if condition, multiple options

Posted 18 December 2015 - 01:03 PM

Any time I see that kind of multiple compare to a string my first thought isn't to find a better compare, but to look at the overall logic and methodology and wonder if there isn't something wrong at a deeper level.

We don't see how/why you are doing this. What is the scenario & purpose? Odds are there is a better logic/algorithm to the process that could be used to avoid this situation altogether.
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is online

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6504
  • View blog
  • Posts: 14,355
  • Joined: 02-June 10

Re: if condition, multiple options

Posted 18 December 2015 - 01:18 PM

View Postoyyou, on 18 December 2015 - 06:02 AM, said:

Yeah, there is that, I just wish I there was something implemented already, or maybe something in the .Net framework like the below for each of the value types in C#.. But I don't know!
public static bool Equals(this string value, params string[] values)
{
 return values.Contains(value);
}



Then write an extension method for it.

Or... Is there some reason you're still using a primitive string[]?
If you use a List<string> you can use it's .Contains() method
            List<string> Somelist = new List<string>() { "Fred", "Wilma", "Barney", "Betty" };
            if (Somelist.Contains("Fred")) {  /* do this */}



UPDATE:

I just tried doing a String[].Contains and it works. There's already a Linq extension method for it.
Attached Image
So I guess the question is... How old is your .NET framework that you don't already have this? Or maybe you just need to add/use Linq.
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5824
  • View blog
  • Posts: 19,822
  • Joined: 05-May 12

Re: if condition, multiple options

Posted 18 December 2015 - 06:00 PM

The OP is looking for a built in "target value is in a collections of values" function. .NET's design philosopy caused it to implement "collection of values contains target value".
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is online

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6504
  • View blog
  • Posts: 14,355
  • Joined: 02-June 10

Re: if condition, multiple options

Posted 19 December 2015 - 08:23 AM

Quote

The OP is looking for a built in "target value is in a collections of values" function. .NET's design philosopy caused it to implement "collection of values contains target value".


What I heard is

The OP wants to know if 1 + 2 = 3
.NET will tell him if 2 + 1 = 3

Franky, when I'm writing a program I don't give a crap about such petty and minor stuff like this.
In this situation I just need to know if "fred" is part of the "Flintstones" collection, and ideally I want the code to be easy to read/maintain and not be a big performance pig.

Honestly I looked at the question the first time and just answered it without a bunch of smart remarks. Atypical for me. But since its going to get dragged out...


Quote

I know I can do this
List<string> myStrings = new List<string>()
{
 "Derp",
 "Rawr",
 "Blargh",
};

if(myStrings.Contains(myString))
{
 // still something
}




But I wanna do this <whine>
if(myString.Equals("Derp", "Rawr", "Blargh"))
{
 // definitely still something
}




Really? Quit your f'ing whining. Just worry about writing the code, making the program work, get paid and move on to the next project. Any developer that is going to snivel about how they want to make C# bend to their way of thinking over one tiny arse little line like this has not, in my opinion really been developing for a few years in the real world. There is so much on the plate of a developer when it comes to make real programs and trying to get the working, robust, reliable, through QA without getting bounced back, through the suits who approve the GUI, through the designers who approve the color scheme, about how I now have to take the entire solution and make it cross-platform and mobile device ready {...} that worrying about something this pettiness is no where on anyone's radar.

If you know you can make a collection then check if your target value is in the collection with a simple and readable: if (Flintstones.Contains("Fred") then do it and move on.

Not to mention that the way you want to do it with providing all the values as strings in quotes leads to typos... Oh, and how you then have to deal with the casing of each statement. We can get into a 100 other problems with the way you're saying you want to do it. But the simple fact is: If the other 3 million developers are doing it that way, and the code language is one way and not the way you want it to be, then you need to get over it.

Honestly... If you're so worried about this kinda stuff that you had to experiment to find a way, research to find a way then finally post it here... Dude, you really don't have enough on your plate at work and probably should worry about whether or not you are redundant. Clearly your job is not putting a lot of responsibility on you if you have the time to worry about how you're going to form this one little bit. Personally I'd worry more about the features on the 'to do list', the stuff in the bug queue, the wants for the next revision of the program.
Was This Post Helpful? 1
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5824
  • View blog
  • Posts: 19,822
  • Joined: 05-May 12

Re: if condition, multiple options

Posted 20 December 2015 - 07:30 PM

Some C/C++ programmers style guides actually recommend Yoda conditions because it will cause a compilation error even if your warnings accidentally get turned off, as well as help the compiler optimize things.

This article argues that Yoda conditions are not necessary in C#.
Was This Post Helpful? 1
  • +
  • -

#10 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: if condition, multiple options

Posted 21 December 2015 - 08:22 AM

Quote

Any developer that is going to snivel about how they want to make C# bend to their way of thinking over one tiny arse little line like this has not, in my opinion really been developing for a few years in the real world


I'm kinda going to disagree here. I've been doing C# development for about 9 years professionally now. My coworkers and I often have discussions about what we would change about the language if we were in charge. It's not really whining. I do think the only way you can accurately (or usefully) criticize a language is when you've used it for some time, for some reasonably complicated production process. I've done that several times over; enough to know what parts are great and what parts are just "meh", and what's really annoying in the language. And I think we can all agree that C#, while great, is not a perfect language. If it were, using TryParse methods wouldn't be so clunky, just off the top of my head*.

On the other hand, this is such a tiny issue. Almost every programmer eventually (and usually pretty early) asks or tries something like this. And eventually realizes it's not a problem; just a difference between the way spoken language and a programming language works. In English, we don't have to repeat the "left hand side" of what we're comparing. "Do you want A or B"? If English worked like a programming language, you'd have to say "Do you want A, or do you want B"?

But the language doesn't support that, because there's no reason to. You gain nothing except a tiny bit of brevity from that, and you lose "explicitness", which is something to generally strive for (we don't like "magic" in our code). Plus, if you really want a method like that, it's pretty easy to achieve:

public static class Extensions
{
	public static bool In<T>(this T val, IEnumerable<T> collection, IEqualityComparer<T> comparer = null)
	{
		if(comparer != null) return collection.Contains(val, comparer);
		else return collection.Contains(val);
	}
}

void Main()
{
	var b1 = 1.In(new[] { 1, 2, 3, 4, 5 });
	var b2 = 50.In(Enumerable.Range(0, 10));
	var b3 = "test".In(new[] { "Boy", "Apple", "TEST" }, StringComparer.CurrentCultureIgnoreCase);
}



It just doesn't look right.

*I actually have an idea about that; give Tuples a literal syntax, and give us native tuple unpacking (like F#'s let a, b = get2Tuple()), and then re-write the TryParses to return a Tuple<bool, T>.
Was This Post Helpful? 2
  • +
  • -

#11 tlhIn`toq  Icon User is online

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6504
  • View blog
  • Posts: 14,355
  • Joined: 02-June 10

Re: if condition, multiple options

Posted 21 December 2015 - 08:35 AM

View PostCurtis Rutland, on 21 December 2015 - 09:22 AM, said:

Quote

Any developer that is going to snivel about how they want to make C# bend to their way of thinking over one tiny arse little line like this has not, in my opinion really been developing for a few years in the real world

My coworkers and I often have discussions about what we would change about the language if we were in charge. It's not really whining.


I disagree that you're disagreeing with me. Its one thing to sit around discussing "What would I change in the C# world if I were the language czar?" - and another thing entirely to have spent a bunch of time trying to actually side step the languages design, done all the research, then finally post asking for help - on this tiny little thing.

Here the OP is not opening up a discussion about hypothetical changes in a language he has no real input into. He's wanting the language to do it his way, rather than just doing it the way he knows is there and exists, used IN A SINGLE LINE that is easy to read, maintainable, and not subject to all the problems that are introduced with the way the OP wants to do it.

Its the difference between discussing "What would we do if we won the lottery?" with your wife while on a car ride, and actually doing 200 hours of research and contacting a financial planner to put a plan together for *if* you win.

This post has been edited by tlhIn`toq: 21 December 2015 - 08:38 AM

Was This Post Helpful? 1
  • +
  • -

#12 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5824
  • View blog
  • Posts: 19,822
  • Joined: 05-May 12

Re: if condition, multiple options

Posted 21 December 2015 - 10:46 PM

Curtis Rutland: Notice that your extension method is named "In". This implies some kind of collection. The OP is seems to be asking for "EqualsOneOfTheFollowing". No collection needs to be created. Just use variable number of parameters (likely via the params keyword).

To make things even more interesting, check out Eric Lippert's answer regarding params IEnumerable<T>. See how the direction that people want is actually towards using collections. To me this is even more support for the design team getting it right and emphasizing collections.
Was This Post Helpful? 0
  • +
  • -

#13 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5824
  • View blog
  • Posts: 19,822
  • Joined: 05-May 12

Re: if condition, multiple options

Posted 21 December 2015 - 11:00 PM

LOL! I was just about ready to shutdown the machine and I remembered: C# already has exactly what the OP is looking for and it's been there since C# 1.0:
switch (myString)
{
case "Derp":
case "Rawr":
case "Blargh":
    // definitely still something
    break;
}


Was This Post Helpful? 1
  • +
  • -

#14 tlhIn`toq  Icon User is online

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6504
  • View blog
  • Posts: 14,355
  • Joined: 02-June 10

Re: if condition, multiple options

Posted 22 December 2015 - 04:15 AM

View Postoyyou, on 18 December 2015 - 04:57 AM, said:

But that's not what I want! I want something more like this
if(myString.Equals("Derp", "Rawr", "Blargh"))
{
 // definitely still something
}

Was This Post Helpful? 0
  • +
  • -

#15 baavgai  Icon User is online

  • Dreaming Coder
  • member icon


Reputation: 6966
  • View blog
  • Posts: 14,572
  • Joined: 16-October 07

Re: if condition, multiple options

Posted 22 December 2015 - 06:31 AM

Inspired by Curtis Rutland:
public static class Extensions {
    public static bool Equals<T>(this T item, params T[] xs) {
        return xs.Any(x => item.Equals(x));
    }
}



This will work exactly as the OP wants: if(myString.Equals("Derp", "Rawr", "Blargh"))

I used to be on the fence with extension methods. Today I'm rather fond of them, particularly for by database lib.

However, just because you can doesn't mean you should. I'd tend to agree that the need for this is narrow enough not to warrant it.

If I have to do a lot of tests for existence I might make a wee private function:
Func<string, bool> test = (new string[] { "Derp", "Rawr", "Blargh" }).Contains;


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2