views:

67

answers:

3

For C# in VS2005, can you do something like this:

if number in [1,2..10,12] { ... }

which would check if number is contained in the set defined in the square brackets?

+1  A: 

.NET 2.0 (which is what VS 2005 targets) doesn't have the notion of a Set.

.NET 3.5 introduced HashSet<T>, and .NET 4 introduced SortedSet<T>.

There isn't a literal form for them though - although collection initializers provide something slightly similar:

new HashSet<int> { 1, 2, 4, 12 }

Of course, you could just use an array:

int[] values = { 1, 2, 5, 12 };

but the range part of your sample - 2..10 - doesn't exist in any version of C#.

Jon Skeet
+1  A: 

Unfortunately not.

However, you can use the Contains() method of a List<int>:

List<int> numbers = ...
if (numbers.Contains(2)) { ... }

if numbers is an array, you can either initialize a new List<int> with the array values:

int[] numbers = { 1, 2, 3, 4 };
List<int> newList = new List<int>(numbers);
if (newList.Contains(2)) { ... }

or use Array.Exists():

Array.Exists(numbers, delegate(int i) { return i == 2; });
hmemcpy
According to me there was no Linq available in C#2.0 (VS2005).
XIII
Oh, you're right, I missed the VS2005...
hmemcpy
A: 

You can "kind of" do what you want using the Enumerable.Range method:

if (Enumerable.Range(2, 8).Concat(new [] { 1, 12 }).Contains(number)) {
    ....
}

Of course, that's not nearly as readable as what you find in a basic functional language...

Dean Harding