Hello I am trying to find best and most efficient way to preform if string exists in list of strings.
My scenario is like this:
- Get all string values from database that are satisfying given conditions.
- Create random code that has 6 digits, but it is a string value.
- Check if generated code exists in list of strings. If it does preform generating of code again, and do it until you find unique string that does not exists in list of strings. When you find one, return it.
This is my code:
private static readonly string chars = "0123456789";
string IGenerateOtpCodeService.GenerateOtpCode()
{
var otps = personalTestSessionRepository
.FindAll(x => x.State == PersonalTestSessionStates.NotStarted)
.Select(x => x.Person.Otp)
.ToList()
.Distinct();
Random random = new Random();
string otp = new string(Enumerable.Repeat(chars, 6)
.Select(s => s[random.Next(s.Length)]).ToArray());
//preform check if otp exitst in otps list. if it does, generate otp again, else return otp
return otp;
}
What is best way to do this? Is it while loop, some LINQ expresion, or something else?