Chaddeus
Chaddeus

Reputation: 13366

Is there a concise way to check if an int variable is equal to a series of ints? | C#

Rather than something like this:

switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

Upvotes: 4

Views: 262

Answers (6)

Jodrell
Jodrell

Reputation: 35726

If your goal is to be concise.

//
(new []{2, 5, 11, 15}).Contains(id)
//

If you want to be fast probably stick with the switch.

I think I like the HashSet though.

Upvotes: 1

HABJAN
HABJAN

Reputation: 9338

You can do something like this:

    bool exist = List.Init(6, 8, 2, 9, 12).Contains(8);

    foreach (int i in List.Init(6, 8, 2, 9, 12))
    {
        Console.WriteLine(i.ToString());
    }



    public class List : IEnumerable<int>
    {
        private int[] _values;

        public List(params int[] values)
        {
            _values = values;
        }

        public static List Init(params int[] values)
        {
            return new List(values);
        }

        public IEnumerator<int> GetEnumerator()
        {
            foreach (int value in _values)
            {
                yield return value;
            }
        }

        public bool Contains(int value)
        {
            return Array.IndexOf(_values, value) > -1;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

Upvotes: 0

Tony The Lion
Tony The Lion

Reputation: 63250

Perhaps a solution using LINQ:

List<int> ints = new List<int> {2, 5, 11, 15};

void Search(int s) {
    int result = ints.Where(x => x == s).FirstOrDefault();
}

Upvotes: 0

Craig Suchanec
Craig Suchanec

Reputation: 10824

You could put all the ints into a HashSet and do a contains.

Hashset<int> ids = new HashSet<int>() {...initialize...};

if(ids.Contains(id)){
...
}

Upvotes: 8

ChrisF
ChrisF

Reputation: 137158

You could try:

List<int> ints = new List<int> {2, 5, 11, 15};
if (ints.Contains(id))
{
}

Though it might be slower than doing the switch.

However, it does have the advantage that (assuming that you initialise the list from data) you can use this to check on any list of integer values and aren't constrained to hard coded values.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

if((new List<int> { 2, 5, 11, 15}).Contains(id))

But you probably don't want to create a new List instance every time, so it would be better to create it in the constructor of your class.

Upvotes: 4

Related Questions