C# - Random Example

If you need to random number between 1 to 10. You can use "Random.Next(minimumValue,maximumValue)".

Remark that if maximum equal 10, the random number can be 0-9. If you want 10 in your random list, you have to set the maximum number is 11.

Random _random = new Random();
Int32 _iRandom = _random.Next(1, _maximumValue + 1);

//_iRandom can be 1-10.

Example. Unique random number

private String RandomList(Int32 totalLuckyWinner, Int32 totalRecord)
{
     #region [ variable ]

     String _strRandom = null;

     #endregion

     #region [ random number ]

     if (totalRecord > 0)
     {
          Random _random = new Random();
          Int32 _iRandom = 0;
          Int32 _count = 0;

          System.Collections.ArrayList _lstNumbers = new System.Collections.ArrayList();

          #region [ while (_count < totalLuckyWinner) ]

          while (_count < totalLuckyWinner)
          {
               _iRandom = _random.Next(1, totalRecord + 1);

               if (!_lstNumbers.Contains(_iRandom))
               {
                         _lstNumbers.Add(_iRandom);
                         _strRandom += _iRandom.ToString();

                         _strRandom += ",";
                         _count++;
               }

          }//end while

          if (_strRandom.Substring(_strRandom.Length - 1) == ",")
          {
               _strRandom = _strRandom.Substring(0, _strRandom.Length - 1);
          }

          #endregion

          _lstNumbers = null;
     }

     #endregion

     return _strRandom;
}

Example:
String _strRandom = this.RandomList(10, 200);
Result: 29,53,122,138,43,8,76,191,10,154

Popular posts from this blog

SAP CPI - Loop Process Call with SuccessFactor (oData V2)

Setting IntelliJ IDEA to run Groovy Script

C# - BASE64 to Image