Thank you all for your comment’s and answers, I have this project for monthly employee shifts,
I wrote some code, but I got some things wrong, like some Employee are repeating in the same month and that’s not supposed to happend.
I have more than 100 employees in my table called ‘EmployeeTB’, and I want to put them in ‘ShiftTB’, which contains shifts for one month, one by one without repeating employees when I use Random.Next()
here’s my code that generates my shifts and it’s correct:
private void PopulateDate(DateTime FromDate, DateTime ToDate)
{
var dt1 = FromDate;
var dt2 = ToDate;
var dt = FromDate;
if (dt <= ToDate)
{
dt = dt.AddDays(-1);
while (dt2 >= dt1)
{
List<ShiftTB> ResultList = new List<ShiftTB>
{
new ShiftTB { NameOfDay = dt1.DayOfWeek.ToString(), DateOfDay = dt=dt.AddDays(1) },
};
foreach (var item in ResultList)
{
dt1 = dt1.AddDays(1);
db.ShiftTBs.InsertOnSubmit(item);
}
db.SubmitChanges();
}
}
}
and this is the code that needs correcting:
Random rnd = new Random();
PopulateDate(DateTime.Parse(txtFromDate.Text), DateTime.Parse(txtToDate.Text));
var EmpList = db.EmployeeTBs.Where(x => x.EmpType == "1" && x.Empstatus == "ok").ToList();
for (int i = 0; i < EmpList.Count; i++)
{
int x = rnd.Next(0, EmpList.Count());
var ListOfResult = db.ShiftTBs.Where(lor => lor.EmpName == null).ToList();
ListOfResult[x].EmpID = EmpList[i].EmpID;
ListOfResult[x].EmpName = EmpList[i].EmpName;
ListOfResult[x].EmpDepartment = EmpList[i].DepartmentName;
ListOfResult[x].EmpType = EmpList[i].EmpType;
}
db.SubmitChanges();
How do I solve this?
2
Answers
I got the answer here's it :
If you only need the list randomized you can use an extension method like the one mentioned in Ken-Y-N’s comment (snippet below for the easy version)
This performs a pseudo-random shuffle, which should be plenty for your purposes, if you wanna stick to your own method of generating the randomness, then simply make sure you’re marking your
Random
as static, so if won’t grab the same seed etc.With the above you can structure your code like so:
This is assuming that you want the list of employees shuffled, and then spacing them out as evenly as possible, if you want it completely random after the list is shuffled you can also do a
Random.Next()
call as the employee id, but it’s up to you.As always, I don’t know your exact issue and goal, so take it with a grain of salt