• 0

C#: equivalent of SQL "in"


Question

Hey,

Quick question. Does anyone know if C# has an equivalent in syntax to SQL's "in" keyword? Basically instead of:

If (a == 1 || a == 2 || a == 4 || a == 7)

Is there any way to do something like:

If (a in (1, 2, 4, 7))

Thanks in advance!

Link to comment
Share on other sites

7 answers to this question

Recommended Posts

  • 0

Well what I'm really looking to do is make my code a little neater. So instead of having a long line of conditionals separated by or (||), I'd rather have it condensed into something more readable. I'm aware that this is possible in certain languages and I'm wondering if it applies to C#.

As far as the case/switch - I don't think I'd be able to include multiple conditionals in one case could I? It would have to be case 1 to 3: blah case 5 to 8: blah; - not case 1 to 3 or 5 to 8: blah; right?

Thanks =)

Link to comment
Share on other sites

  • 0

You can use the "indexOf" method of classes (collection classes) that support it, but I don't think you can do that with things like primitive arrays.

You could always write your own function like

bool hasItem(int[] ar, int lookingfor)
{
  for (int i=0; i < ar.Length; i++)
    if (ar[i] == lookingfor)
      return true;

  return false;
}

you could just use a const int array for your orignal dataset.

Edited by virtorio
Link to comment
Share on other sites

  • 0

You could sort your array of primitives, and use the BinarySearch method to retrieve the index of the first occurrence.

What kind of structure are you trying to check? IN is used for lists or tables, basically sets of data. What you illustrated to begin with wouldn't work against atomic types, except strings. With strings you could use the IndexOf method.

Link to comment
Share on other sites

  • 0

ah ok. I thought there might be something built into the dot net framework or something. The function virtorio proposed is a good idea - I may use that. The way I have it now is horrible for searching for many numbers like I am. Thanks for all the input everyone =)

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.