Is there a compressed way to check if an int variable is equal to an entire series of int? | WITH#

Instead of this:

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

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

+4
source share
6 answers

You can put all ints in a HashSet and make a contains.

 Hashset<int> ids = new HashSet<int>() {...initialize...}; if(ids.Contains(id)){ ... } 
+7
source
 if((new List<int> { 2, 5, 11, 15}).Contains(id)) 

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

+4
source

You can try:

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

Although this may be slower than performing a switch.

However, this has the advantage that (provided that you initialize the list from the data), you can use it to check any list of integer values ​​and are not limited to hard-coded values.

+2
source

If your goal should be brief.

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

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

I think I like HashSet.

+1
source

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(); } 
0
source

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(); } } 
0
source

Source: https://habr.com/ru/post/1347708/


All Articles