Hi,
I'm wondering is there a way to shorten this IF statement: -
if (a == b || a == c || a == d)
-
{
-
code
-
}
-
to -
if (a == (b or c or d) )
-
{
-
code
-
}
-
Thank you
15 3127
<digress>
You know, I'm surprised a language hasn't developed something like this. I remember, oh so many years ago, when I first started programming in QBasic I tried to do that exact same thing. My first if statement was something along the lines of...
... which is obviously ambiguous, but with the use of brackets the OP's shortened version is clear. Of course, now I'm too used to the current way of doing it, but I do find it noteworthy that new programmers often make that mistake.
</digress>
You know, I've thought about this. You could do something like this, but it's clunky: - int age = 24;
-
if ((new int[] { 18, 25 }).Contains(age))
-
Console.WriteLine("yes");
-
else
-
Console.WriteLine("no");
Hardly faster than the other way. But if you had four or five values, it might be better.
I've come up with a static class that makes creating these sequences a bit easier: - public static class Seq
-
{
-
public static IEnumerable<int> Make(int min, int max)
-
{
-
for (int i = min; i <= max; i++)
-
yield return i;
-
}
-
-
public static IEnumerable<int> Make(Func<int, int> iterator, int min, int max)
-
{
-
do
-
{
-
yield return min;
-
min = iterator.Invoke(min);
-
} while (min <= max);
-
}
-
-
public static IEnumerable<T> Make<T>(params T[] list)
-
{
-
foreach (T item in list)
-
yield return item;
-
}
-
}
I got the idea from F#'s seq method.
You can easily create a continuous list of ints: Seq.Make(1, 10)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Or one that has an iterator method: Seq.Make(x => x += 2, 1, 10)
{1, 3, 5, 7, 9}
Or even one with just the values you want: Seq.Make<int>(1, 2, 4)
{1, 2, 4}
I made that last one generic because it's easy to. The other ones require a numeric type. Generic type constraints are possible, but there is no constraint that says "numeric." So, you could implement the extra methods using doubles/whatever if you wanted to.
I actually like the one that uses a function as a parameter. You can do stuff like this: - Seq.Make(x => x % 2 == 0 ? x + 3 : x + 5, 1, 50)
1, 6, 9, 14, 17, 22, 25, 30, 33, 38, 41, 46, 49
Or even go so far as to do this: - private static int DoSomething(int x)
-
{
-
//do lots of stuff to x
-
return x + 1;
-
}
-
...
-
...
-
Seq.Make(DoSomething, 1, 10)
Anyway. To your example, you could do something like this: - if (Seq.Make<int>(18, 25).Contains(age))
-
Console.WriteLine("yes");
-
else
-
Console.WriteLine("no");
So, I went off on a tangent of my own, but am having fun.
Oh, I came up with some useful extension methods to go along: - public static class Extensions
-
{
-
public static bool In(this int i, IEnumerable<int> collection)
-
{
-
return collection.Contains(i);
-
}
-
-
public static void Print<T>(this IEnumerable<T> collection, TextWriter writer = null)
-
{
-
if (writer == null)
-
writer = Console.Out;
-
StringBuilder sb = new StringBuilder("{");
-
foreach (T item in collection)
-
sb.Append(string.Format("{0}, ", item));
-
sb.Append("}");
-
sb.Remove(sb.Length - 3, 2);
-
Console.WriteLine(sb.ToString());
-
}
-
}
So, you can do things like: - if(age.In(Seq.Make(18, 25)))
-
Console.WriteLine("yes");
-
else
-
Console.WriteLine("no");
-
Or even 25.In(Seq.Make(18, 25))
Also, the Print method will conveniently print a collection using the provided TextWriter or Console.Out.
You know, that's the thing about programmers. We'll happily spend more time avoiding a "problem" than just doing the "workaround" ;)
In the spirit of fun, it occurred to me that you could quite easily create a comparer class to do all sorts of comparisons for you. - class Program
-
{
-
static void Main(string[] args)
-
{
-
if (Comparer<int>.Compare(Comparer<int>.CompareType.Or, 11, new int[] { 18, 25 }))
-
{
-
Console.WriteLine("Pass");
-
}
-
else
-
{
-
Console.WriteLine("Fail");
-
}
-
-
if (Comparer<string>.Compare(Comparer<string>.CompareType.And, "Gary", new string[] { "Gary", "Gary" }))
-
{
-
Console.WriteLine("Pass");
-
}
-
else
-
{
-
Console.WriteLine("Fail");
-
}
-
}
-
}
-
-
public static class Comparer<T> where T : IComparable
-
{
-
public enum CompareType
-
{
-
Or,
-
And
-
}
-
-
public static bool Compare(CompareType compareType, T value, T[] items)
-
{
-
bool ret = true;
-
foreach (T obj in items)
-
{
-
if (value.CompareTo(obj) != 0)
-
{
-
ret = false;
-
if (compareType == CompareType.And) break;
-
}
-
else
-
{
-
ret = true;
-
}
-
}
-
-
return ret;
-
}
-
}
I'm willing to bet you could put some LINQ in there as well, but I didn't 'cause I'm not familiar with it. Good ol' foreach for me ;)
If you really wanted to get crazy, you could use a KeyValuePair for your comparisons and include greater than, less than, etc... tests for each value.
Hmm also, I can't seem to use your code. Do I need a different version of .NET or VS? I may be out of date... using 2008 and I should have .NET 4.x (w/e it's at) via windows update.
Good job Curtis, for people that do not need the use of Sequences I've derived a simpler extension method from curtis code to allow people to do that kind of stuff: - if( 1.In(1,2,3,4) )....;
-
if( 3.123.In(3.1,3.2,3.4) )....;
-
if( "Hello".In("Hello", "World") )....;
-
-
if (age.In(18, 25))
-
Console.WriteLine("yes");
-
else
-
Console.WriteLine("no");
etc...
Here it is: - public static bool In<T>(this T i, params T[] tab)
-
{
-
return tab.Contains(i);
-
}
I like it, Sigo. You should make an account and start answering questions.
@Gary
I'm using VS2010, but I've tested it in 2008 as well. It requires the following namespaces: - using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
System.Text is for the StringBuilder in the Print extension method.
If that fails, tell me what the exception is.
Also, even though you have .NET 4 from Windows Update, you can't (as far as I'm aware) develop applications for it, because you need to use the .NET 4 SDK, which is not included, and apparently only supports VS2010.
It's not allowed in 3.5 to use use default-parameters like writer is in
void Print<T>(this IEnumerable<T> collection, TextWriter writer = null)
(btw. what's the tag to make this in-line-code-formatting?)
You could also create a Between-method like 10.Between(9, 11) == 10.In(Seq.Make(9, 11)) == 10.In(Enumerable.Range(9, 3))
Extension methods are really a great thing.
I have never heard of extension methods before... and yea I've got it working at work in VS 2010. I may not have the .NET 4 SDK installed at home (O.o) so I'll look into it.
These extension methods... they're freaking cool. They just get picked up out of nowhere? It seems you can name the static class anything and it still attaches the method to the correct type. Quite strange! I'm going to have to do some reading.
Also, best digression thread evar ;)
@Christian
The tag is [icode][/icode].
And I did forget to test the Print method, that's why it was failing. Default/named parameters are a C# 4.0 thing.
And I had forgotten about Enumerable.Range. I knew there was something like it, but I couldn't remember what.
I may be a bit late to the party, but COBOL does allow you to write
In case anyone still cares about the class and methods we've come up with, I've refined them a bit and posted them to my blog.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Lo La LoooOOOo |
last post by:
I also need to movev the data from one to the other..
exemple on image: http://djembefolettes.free.fr/box.gif
Thank you very much!
--
Lo La LoooOoooOOo
Tralala! Na!
|
by: Marie |
last post by:
My tables look basically like:
TblCustomer
CustomerID
Customer
TblOption
OptionID
Option
TblCustomerOption
|
by: Jai |
last post by:
Hi,
I am in a problem of sending mass emails(newsletter) to my website
members.
Actually my problem is this:
I want to send newsletter to my website members. But I had given a
facility for...
|
by: tolkienarda |
last post by:
hi all
i am trying to make a selection box where people can select multiple items then those items will become values assigned to a variable. i am actualy using this in a php/mysql program but i...
|
by: jhh100 |
last post by:
Hello..
I have Moderate Knowlege in Access but I'm stumped on how to figure out how to get this done.. I'll try to explain
I'm trying to develop a access database that will manage engine...
|
by: magmike |
last post by:
I currently have a button once clicked, invokes the following:
If Address_Select = -1 Then
Forms!ProspectForm!Address =
End If
However, there are 11 other fields in the subform that i'd like...
|
by: nrsutton |
last post by:
Hi
I have a real headache of a problem and was wondering if anyone can
help me.
I'm writing a system that saves stock items. Each item can have none
or an infinite number of options attached...
|
by: helplakshmi |
last post by:
Hi All,
I am new to php. The form that i am designing has few input input fields with submit and reset button. The functionality of submit and reset are working properly till now.
My form
...
|
by: love91501 |
last post by:
I was wondering if anyone would be able to help me figure out how to make my Q010 have the ability to chose 2 answers, I'm hoping to stay away from checkboxes but I am willing to take in any advice....
|
by: munkee |
last post by:
Hi all,
I am a bit stumped on this but I think I need to implement a junction table.. which I have never done before.
Basically someone reports an event in to my main table, it is assigned an...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |