问题描述
我正在尝试创建一个唯一的随机数。如果数据库中存在随机数,请再次遍历代码块,直到找到不存在的数字。将价值保存到数据库。任何帮助都会很棒。谢谢。
public IHttpActionResult BookMatch(int id)
{
Guid guid = Guid.NewGuid();
var user = User.Identity.GetUserId();
var getuser = db.AspNetUsers.Find(user);
var match = db.Matches.Find(id);
Random rnd = new Random();
var peg = rnd.Next(match.PegRangeMin,match.PegRangeMax);
var alreadyExists = db.Pegs.Any(x => x.MatchId == match.Id && x.PegNo == peg);
if (alreadyExists == true)
{
//do something
}
var result = new Booked()
{
MatchId = id,BookerId = user,TicketNo = guid.ToString(),//pegNo = randompeg
};
db.Bookeds.Add(result);
db.SaveChanges();
if (result == null)
{
throw new Exception();
}
var getmatch = db.Matches.Find(id);
var body = "<p>Email From: {0} ({1}) </p>" +
"<h3>Match Booking Confirmation:</h3>" +
"<b>Ticket Number:</b><p> {2} </p>" +
"<b>Venue:</b><p> {3} </p>" +
"<b>date and time:</b><p>{4}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress(getuser.Email));
message.From = new MailAddress("nicholas.mciver@Activeplan.co.uk");
message.Subject = "Matchbooker Confirmation Email";
message.Body = string.Format(body,getuser.GetFullName(),getuser.Email,result.TicketNo,getmatch.Fishery.Name,getmatch.DateTime);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
smtp.Send(message);
}
return Ok();
}
解决方法
最简单的方法是在int peg;
while (true)
{
peg = rnd.Next(match.PegRangeMin,match.PegRangeMax);
var alreadyExists = db.Pegs.Any(x => x.MatchId == match.Id && x.PegNo == peg);
if (!alreadyExists) break;
}
循环中进行数字生成和检查:
# start Excel
$excel = New-Object -comobject Excel.Application
#open file
$FilePath = 'FilePath'
$workbook = $excel.Workbooks.Open($FilePath)
#make it visible (just to check what is happening)
$excel.Visible = $true
#print file name
$workbook.sheets.item(1).activate()
$workSheet = $Workbook.Sheets.Item(1)
$WorkSheet.Name
#print cell value
$WorkbookTotal=$workbook.Worksheets.item(1)
$value = $WorkbookTotal.Cells.Item(1,1)
$value.Text
# First retrieve the website
$result = Invoke-webrequest -Uri "https://www.website.com/$value" -Method Get
$resultTable = @{}
# Get the title
$resultTable.title = $result.ParsedHtml.title
# Return the table we have built as an object
Write-Output New-Object -TypeName PSCustomObject -Property $resultTable
#close excel
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
spps -n Excel
这不是完美的,因为万一所有可能的数字都被取走,循环将永不中断。但是,只要min-max范围足够大,这实际上就不会成为问题。