There are many ways to implement this logic, more or less optimized, but you can find an example of implementation to solve that issue or to be your starting point.
Plínio Costa Senior Techinical Support Engineer National Instruments Brazil
Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.