I am an intern in software business. I have a table that creates excel. I create this excel data by grouping them according to months and years. I have a problem. I have ACTUALVALUE in a column. Another grouped value is FORECASTVALUE and I don't want them to occur on separate lines in a single line. How can I combine two data in one line?
My Code:
var yeargroup = actulaModel.Items.GroupBy(x => x.YIL).ToList();
foreach (var year in yeargroup)
{
var monthdata = year.GroupBy(x => x.AY).ToList();
foreach (var month in monthdata)
{
var customGroup = month.GroupBy(x => x.GetType().GetProperty(dashboardScaneriosPieChartRequestDto.GROUPBY).GetValue(x, null)).ToList();
foreach (var lastData in customGroup)
{
var etlgroup = lastData.GroupBy(x => x.ETL_DATE).OrderByDescending(x => x.Key).ToList();
var etlfirstgroup = etlgroup.FirstOrDefault();
if (etlfirstgroup != null)
{
var distinct = etlfirstgroup.GroupBy(x => new { x.YIL, x.AY, x.DTINVENTITEMGROUPID, x.ALTK_ACTUAL_VOLUME, x.CUSTGROUPID, x.DTINVENTITEMSUBGROUPID, x.ETL_DATE }).Select(x => x.First()).ToList();
foreach (var x in distinct)
{
result.Add(new ExcelDataDto()
{
POINTOFSALE = x.Salesroom,
CUSTOMERGROUPNAME = x.CustomerGroupName,
DTINVENTITEMGROUPNAME = x.DTINVENTITEMGROUPNAME,
DTINVENTITEMSUBGROUPNAME = x.DTINVENTITEMSUBGROUPNAME,
ACTUALVALUE = Convert.ToInt32(x.ALTK_ACTUAL_VOLUME),
//FORECASTVALUE = 0,
YIL = x.YIL,
AY = x.AY,
ETL_DATE = x.ETL_DATE
});
}
}
}
}
}
var yeargroupforecast = forecastModel.Items.GroupBy(x => x.YIL).ToList();
foreach (var year in yeargroupforecast)
{
var monthdata = year.GroupBy(x => x.AY).ToList();
foreach (var month in monthdata)
{
var customGroup = month.GroupBy(x => x.GetType().GetProperty(dashboardScaneriosPieChartRequestDto.GROUPBY).GetValue(x, null)).ToList();
foreach (var lastData in customGroup)
{
var etlgroup = lastData.GroupBy(x => x.ETL_DATE).OrderByDescending(x => x.Key).ToList();
var etlfirstgroup = etlgroup.FirstOrDefault();
if (etlfirstgroup != null)
{
var distinct = etlfirstgroup.GroupBy(x => new { x.YIL, x.AY, x.DTINVENTITEMGROUPID, x.ALTK_PREDICTION_VOLUME, x.CUSTGROUPID, x.DTINVENTITEMSUBGROUPID, x.ETL_DATE }).Select(x => x.First()).ToList();
foreach (var x in distinct)
{
result.Add(new ExcelDataDto()
{
POINTOFSALE = x.Salesroom,
CUSTOMERGROUPNAME = x.CustomerGroupName,
DTINVENTITEMGROUPNAME = x.DTINVENTITEMGROUPNAME,
DTINVENTITEMSUBGROUPNAME = x.DTINVENTITEMSUBGROUPNAME,
FORECASTVALUE = Convert.ToInt32(x.ALTK_PREDICTION_VOLUME),
//ACTUALVALUE = 0,
YIL = x.YIL,
AY = x.AY,
ETL_DATE = x.ETL_DATE
});
}
}
}
}
}
return result;
Excel spreadsheet as an example:
Sale Product Actualvalue Forecastvalue
Yİ Product A 50
Yİ Product B 100
Yİ Product A 40
Yİ Product B 80
Here, I want it to write both the empty Actualvalue or the empty Forecastvalue values on the same line without writing them. How can I do this?
Afterwards, I did something like this, but I am getting an error, am I thinking logically wrong?
foreach (var x in result)
{
result.Add(new ExcelDataDto()
{
POINTOFSALE = x.POINTOFSALE,
CUSTOMERGROUPNAME = x.CUSTOMERGROUPNAME,
DTINVENTITEMGROUPNAME = x.DTINVENTITEMGROUPNAME,
DTINVENTITEMSUBGROUPNAME = x.DTINVENTITEMSUBGROUPNAME,
FORECASTVALUE = Convert.ToInt32(x.FORECASTVALUE),
ACTUALVALUE = Convert.ToInt32(x.ACTUALVALUE),
YIL = x.YIL,
AY = x.AY,
ETL_DATE = x.ETL_DATE
});
}
return result;
Can you help me what am I doing wrong?
I have a list of objects (Pulled from SQL DB) with a TransactionDate for each object “alarmHistoryList”.
I have another list of objects (Pulled from SQL DB) and each object has a StartDate a FinishDate and an ID “RunLogList”.
There will be a Many to One relationship where “List1” will be the many and “RunLogList” the one. Each Run may have many Alarms.
I want every object in “alarmHistoryList” returned with the ID of the object in “RunLogList” where the TransactionDate fall between the StartDate and the FinishDate.
private void MatchRunData()
{
foreach (var alarm in _alarmHistoryList)
{
var AlarmTransTime = alarm.TransactionTime;
var filteredData = _FARunLogList.Where(t =>
t.TrackInTime > AlarmTransTime && t.TrackOutTime < AlarmTransTime);
}
}
Run logs with alarms matching the run log time window:
var runLogAlarms = new Dictionary<RunLog, IList<Alarm>>();
foreach (var alarm in _alarmHistoryList)
{
var alarmTransTime = alarm.TransactionTime;
var filteredData = _FARunLogList
.Where(t => t.TrackInTime > alarmTransTime && t.TrackOutTime < alarmTransTime)
.ToList();
foreach (var runLog in filteredData)
{
if (runLogAlarms.TryGetValue(runLog, out var alarmsValue))
{
alarmsValue.Add(alarm);
}
else
{
runLogAlarms[runLog] = new List<Alarm> { alarm };
}
}
}
I came up with an answer before Prolog that works. I am sure the answer Prolog gave works as well and is cleaner but I am posting my answer since it is the one I will be using.
private void MatchRunData()
{
foreach (var alarm in _alarmHistoryList)
{
var AlarmTransTime = alarm.TransactionTime;
foreach (var run in _FARunLogList)
{
var TrackInTime = run.TrackInTime;
var TrackOutTime = run.TrackOutTime;
var ID = run.LogId;
if (AlarmTransTime > TrackInTime && AlarmTransTime < TrackOutTime)
{
_MergedalarmHistoryList.Add
(new AlarmHistoryDefinition()
{ AlarmDesc = alarm.AlarmDesc, AlarmID = alarm.AlarmID, ToolID = alarm.ToolID,
TransactionTime = alarm.TransactionTime, GlobalToolID = alarm.GlobalToolID,
RUnLogID = run.LogId });
}
}
_MergedalarmHistoryList.Add(new AlarmHistoryDefinition()
{ AlarmDesc = alarm.AlarmDesc, AlarmID = alarm.AlarmID, ToolID = alarm.ToolID,
TransactionTime = alarm.TransactionTime, GlobalToolID = alarm.GlobalToolID,
RUnLogID = 00000 });
}
}
Can try this
private void MatchRunData()
{
foreach (var alarm in _alarmHistoryList)
{
var filteredData = _FARunLogList.Where(t =>
t.TrackInTime > alarm.TransactionTime && t.TrackOutTime < alarm.TransactionTime);
alarm.RunLogListId = filteredData.RunLogListId;
}
}
This is the database call -
if (status == ValuationFilter.All)
{
valuations = db.Valuations.Where(v => ((v.Creationdate >= startDate && v.Creationdate <= endDate) ||
v.SI47Instruction.Count(s => s.RequestDateTime >= startDate && s.RequestDateTime <= endDate) > 0)).Include(t => t.SI47Instruction).ToArray();
}
Below is the Foreach loop where data is collected and sent over to the Frontend
foreach (var item in valuations)
{
var valuationActiveAction = Action.GetActiveActionByValuationAndCompany(item.Id, companyId);
var valuationReport = Report.GetByValuationId(item.Id);
var dashboardItem = new Domain.DTO.DashboardItem
{
//PropertyTitle = item.Property.Address1,
//PropertyFullAddress = String.Format("{0} {1} {2}", item.Property.Address1, item.Property.Address2, item.Property.City),
PropertyTitle = (String.Format("{0}{1} {2}{3} {4}", item.Property.Address1.Replace(",", ""), ",", String.IsNullOrEmpty(item.Property.Address2) ? "" : item.Property.Address2.Replace(",", ""), ",", item.Property.City)).Replace(", ,", ","),
PropertyFullAddress = (String.Format("{0}{1} {2}{3} {4}", item.Property.Address1.Replace(",", ""), ",", String.IsNullOrEmpty(item.Property.Address2) ? "" : item.Property.Address2.Replace(",", ""), ",", item.Property.City)).Replace(", ,", ","),
Originator = db.Companies.Where(c => c.Id == item.OriginationCompanyId).First().Name,
Valuer = item.ValuationCompanyId > 0 ? String.Format("{0} {1} {2}", db.Companies.Where(c => c.Id == item.ValuationCompanyId).First().Name, "-", db.Companies.Where(c => c.Id == item.ValuationCompanyId).First().Telephone) : "",
Notes = item.Note,
Action = valuationActiveAction.Type,
BorrowersName = item.BorrowerName
};
if (item.HasBeenDeclined.HasValue && item.HasBeenDeclined.Value && companyType == CompanyType.VMSI)
{
var declinedReasons = ValuationDeclined.GetByValuationIdForDashboard(item.Id);
dashboardItem.DeclineReasons = declinedReasons.Length > 0 ? declinedReasons : null;
}
if (item.SI47Instruction.Count > 0)
{
var lastestSI47 = item.SI47Instruction.OrderByDescending(s => s.Id).FirstOrDefault();
switch(status)
{
case ValuationFilter.Completed:
if (lastestSI47.Status != (int)InstructionStatus.SI47ReportComplete)
{
continue;
}
break;
case ValuationFilter.CompletedWithDrawn:
if (lastestSI47.Status != (int)InstructionStatus.SI47ReportComplete &&
lastestSI47.Status != (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
case ValuationFilter.InProgress:
if (lastestSI47.Status == (int)InstructionStatus.SI47ReportComplete ||
lastestSI47.Status == (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
case ValuationFilter.InProgressCompleted:
if (lastestSI47.Status == (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
case ValuationFilter.InProgressWithdrawn:
if (lastestSI47.Status == (int)InstructionStatus.SI47ReportComplete)
{
continue;
}
break;
case ValuationFilter.Withdrawn:
if (lastestSI47.Status != (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
}
List<SI47.Instruction> si47Instructions = new List<SI47.Instruction>();
foreach (var si47Instruction in item.SI47Instruction)
{
si47Instructions.Add(new SI47.Instruction(si47Instruction));
}
if (si47Instructions.Count > 0)
{
dashboardItem.Type = InstructionType.SI47;
var activeSI47 = si47Instructions.OrderByDescending(c => c.Creationdate).First();
var activeSI47InstructionReport = SI47.Report.GetByInstructionId(activeSI47.Id);
dashboardItem.RequestId = activeSI47.Id;
dashboardItem.StandardInstructionId = activeSI47.StandardRequestId;
dashboardItem.Status = (Domain.Enumerations.InstructionEnumerations.InstructionStatus)activeSI47.Status;
dashboardItem.Date = activeSI47.Creationdate;
if (SuperBank >= 1)
{
dashboardItem.ReportId = activeSI47InstructionReport.Id;
}
else
{
dashboardItem.ReportId = companyType == Domain.Enumerations.Security.CompanyType.Origination ? 0 : activeSI47InstructionReport.Id;
}
dashboardItem.CompletionDate = activeSI47.DateReportSigned;
if (companyType == CompanyType.Origination || companyType == CompanyType.VMSI)
{
dashboardItem.RevalDate = activeSI47.RevalDate;
}
List<Domain.DTO.DashboardPreviousInstruction> prevInstructionList = new List<Domain.DTO.DashboardPreviousInstruction>();
// add Standard Request to list of previous instructions
prevInstructionList.Add(new Domain.DTO.DashboardPreviousInstruction()
{
Id = item.Id,
Alerts = Business.Valuation.Alert.GetDescriptionsForMultipleToDashboard(valuationReport.Alerts.Select(i => (int)i).ToArray()),
InspectionDate = item.DateInspection,
InstructionDate = item.Creationdate,
ReportCompletedDate = item.DateReportSigned.Value,
ReportId = valuationReport.Id,
AppointmentDate = item.Deadline,
Type = "Standard"
});
// add remaining SI47 Instruction to previous instructions
if (si47Instructions.Count > 1)
{
var previousSI47List = si47Instructions.Where(t => !t.IsActive).ToArray();
foreach (var prevSI47 in previousSI47List)
{
var prevSI47InstructionReport = SI47.Report.GetByInstructionId(prevSI47.Id);
prevInstructionList.Add(new Domain.DTO.DashboardPreviousInstruction()
{
Id = prevSI47.Id,
Alerts = new string[0],
InstructionDate = prevSI47.Creationdate,
ReportCompletedDate = prevSI47.DateReportSigned.Value,
ReportId = prevSI47InstructionReport.Id,
Type = "SI47"
});
}
}
dashboardItem.PreviousInstructions = prevInstructionList.ToArray();
}
}
else
{
dashboardItem.Type = InstructionType.Standard;
dashboardItem.StandardInstructionId = item.Id;
dashboardItem.RequestId = item.Id;
dashboardItem.Status = (Domain.Enumerations.InstructionEnumerations.InstructionStatus)item.Status;
dashboardItem.Date = item.Creationdate;
dashboardItem.Appointment = item.Deadline;
if (SuperBank >= 1)
{
dashboardItem.ReportId = valuationReport.Id;
}
else
{
dashboardItem.ReportId = companyType == Domain.Enumerations.Security.CompanyType.Origination ? 0 : valuationReport.Id;
}
dashboardItem.CompletionDate = item.DateReportSigned;
dashboardItem.InspectionDate = item.DateInspection;
if (item.HasAlerts.HasValue && item.HasAlerts.Value)
{
dashboardItem.Alerts = Business.Valuation.Alert.GetDescriptionsForMultipleToDashboard(valuationReport.Alerts.Select(i => (int)i).ToArray());
}
if (companyType == CompanyType.Origination || companyType == CompanyType.VMSI)
{
dashboardItem.RevalDate = item.RevalDate;
}
dashboardItem.PreviousInstructions = new Domain.DTO.DashboardPreviousInstruction[0];
}
result.Add(dashboardItem);
}
}
return result.OrderBy(i => i.Date).ToArray();
}
foreach (var item in valuations)
{
var valuationActiveAction = Action.GetActiveActionByValuationAndCompany(item.Id, companyId);
var valuationReport = Report.GetByValuationId(item.Id);
var dashboardItem = new Domain.DTO.DashboardItem
{
//PropertyTitle = item.Property.Address1,
//PropertyFullAddress = String.Format("{0} {1} {2}", item.Property.Address1, item.Property.Address2, item.Property.City),
PropertyTitle = (String.Format("{0}{1} {2}{3} {4}", item.Property.Address1.Replace(",", ""), ",", String.IsNullOrEmpty(item.Property.Address2) ? "" : item.Property.Address2.Replace(",", ""), ",", item.Property.City)).Replace(", ,", ","),
PropertyFullAddress = (String.Format("{0}{1} {2}{3} {4}", item.Property.Address1.Replace(",", ""), ",", String.IsNullOrEmpty(item.Property.Address2) ? "" : item.Property.Address2.Replace(",", ""), ",", item.Property.City)).Replace(", ,", ","),
Originator = db.Companies.Where(c => c.Id == item.OriginationCompanyId).First().Name,
Valuer = item.ValuationCompanyId > 0 ? String.Format("{0} {1} {2}", db.Companies.Where(c => c.Id == item.ValuationCompanyId).First().Name, "-", db.Companies.Where(c => c.Id == item.ValuationCompanyId).First().Telephone) : "",
Notes = item.Note,
Action = valuationActiveAction.Type,
BorrowersName = item.BorrowerName
};
if (item.HasBeenDeclined.HasValue && item.HasBeenDeclined.Value && companyType == CompanyType.VMSI)
{
var declinedReasons = ValuationDeclined.GetByValuationIdForDashboard(item.Id);
dashboardItem.DeclineReasons = declinedReasons.Length > 0 ? declinedReasons : null;
}
if (item.SI47Instruction.Count > 0)
{
var lastestSI47 = item.SI47Instruction.OrderByDescending(s => s.Id).FirstOrDefault();
switch(status)
{
case ValuationFilter.Completed:
if (lastestSI47.Status != (int)InstructionStatus.SI47ReportComplete)
{
continue;
}
break;
case ValuationFilter.CompletedWithDrawn:
if (lastestSI47.Status != (int)InstructionStatus.SI47ReportComplete &&
lastestSI47.Status != (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
case ValuationFilter.InProgress:
if (lastestSI47.Status == (int)InstructionStatus.SI47ReportComplete ||
lastestSI47.Status == (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
case ValuationFilter.InProgressCompleted:
if (lastestSI47.Status == (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
case ValuationFilter.InProgressWithdrawn:
if (lastestSI47.Status == (int)InstructionStatus.SI47ReportComplete)
{
continue;
}
break;
case ValuationFilter.Withdrawn:
if (lastestSI47.Status != (int)InstructionStatus.Withdrawn)
{
continue;
}
break;
}
List<SI47.Instruction> si47Instructions = new List<SI47.Instruction>();
foreach (var si47Instruction in item.SI47Instruction)
{
si47Instructions.Add(new SI47.Instruction(si47Instruction));
}
if (si47Instructions.Count > 0)
{
dashboardItem.Type = InstructionType.SI47;
var activeSI47 = si47Instructions.OrderByDescending(c => c.Creationdate).First();
var activeSI47InstructionReport = SI47.Report.GetByInstructionId(activeSI47.Id);
dashboardItem.RequestId = activeSI47.Id;
dashboardItem.StandardInstructionId = activeSI47.StandardRequestId;
dashboardItem.Status = (Domain.Enumerations.InstructionEnumerations.InstructionStatus)activeSI47.Status;
dashboardItem.Date = activeSI47.Creationdate;
if (SuperBank >= 1)
{
dashboardItem.ReportId = activeSI47InstructionReport.Id;
}
else
{
dashboardItem.ReportId = companyType == Domain.Enumerations.Security.CompanyType.Origination ? 0 : activeSI47InstructionReport.Id;
}
dashboardItem.CompletionDate = activeSI47.DateReportSigned;
if (companyType == CompanyType.Origination || companyType == CompanyType.VMSI)
{
dashboardItem.RevalDate = activeSI47.RevalDate;
}
List<Domain.DTO.DashboardPreviousInstruction> prevInstructionList = new List<Domain.DTO.DashboardPreviousInstruction>();
// add Standard Request to list of previous instructions
prevInstructionList.Add(new Domain.DTO.DashboardPreviousInstruction()
{
Id = item.Id,
Alerts = Business.Valuation.Alert.GetDescriptionsForMultipleToDashboard(valuationReport.Alerts.Select(i => (int)i).ToArray()),
InspectionDate = item.DateInspection,
InstructionDate = item.Creationdate,
ReportCompletedDate = item.DateReportSigned.Value,
ReportId = valuationReport.Id,
AppointmentDate = item.Deadline,
Type = "Standard"
});
// add remaining SI47 Instruction to previous instructions
if (si47Instructions.Count > 1)
{
var previousSI47List = si47Instructions.Where(t => !t.IsActive).ToArray();
foreach (var prevSI47 in previousSI47List)
{
var prevSI47InstructionReport = SI47.Report.GetByInstructionId(prevSI47.Id);
prevInstructionList.Add(new Domain.DTO.DashboardPreviousInstruction()
{
Id = prevSI47.Id,
Alerts = new string[0],
InstructionDate = prevSI47.Creationdate,
ReportCompletedDate = prevSI47.DateReportSigned.Value,
ReportId = prevSI47InstructionReport.Id,
Type = "SI47"
});
}
}
dashboardItem.PreviousInstructions = prevInstructionList.ToArray();
}
}
else
{
dashboardItem.Type = InstructionType.Standard;
dashboardItem.StandardInstructionId = item.Id;
dashboardItem.RequestId = item.Id;
dashboardItem.Status = (Domain.Enumerations.InstructionEnumerations.InstructionStatus)item.Status;
dashboardItem.Date = item.Creationdate;
dashboardItem.Appointment = item.Deadline;
if (SuperBank >= 1)
{
dashboardItem.ReportId = valuationReport.Id;
}
else
{
dashboardItem.ReportId = companyType == Domain.Enumerations.Security.CompanyType.Origination ? 0 : valuationReport.Id;
}
dashboardItem.CompletionDate = item.DateReportSigned;
dashboardItem.InspectionDate = item.DateInspection;
if (item.HasAlerts.HasValue && item.HasAlerts.Value)
{
dashboardItem.Alerts = Business.Valuation.Alert.GetDescriptionsForMultipleToDashboard(valuationReport.Alerts.Select(i => (int)i).ToArray());
}
if (companyType == CompanyType.Origination || companyType == CompanyType.VMSI)
{
dashboardItem.RevalDate = item.RevalDate;
}
dashboardItem.PreviousInstructions = new Domain.DTO.DashboardPreviousInstruction[0];
}
result.Add(dashboardItem);
}
}
return result.OrderBy(i => i.Date).ToArray();
}
NOTE: I ran this piece of code many times, the initial database pull takes only 0.3 seconds no matter how many items I pull from the database, but the creation of the list inside the foreach takes a very long time, for some queries upto 2 minutes, not able to figure out what's causing this issue.
Is db a call to the database? perhaps EF?
If so, you are then querying the database as many times as the Length() of valuations.
You do this on the lines you have the following code:
Originator = db.Companies.Where(c => c.Id == tem.OriginationCompanyId).First().Name
That's why it is incredibly slow.
I don't have access to your code, so below is a very simple solution that may/may not apply to your use case, but keep in mind your issue is on the above line. You should avoid at all costs call a database inside a loop.
You should be able to solve it by including a reference to the OriginationCompany of type Companies inside Valuations entity class (I am assuming you are using EntityFramework and it has a FK of CompanyID inside Valuations as a normal scenario would).
Then when you first query your database you should just add an Include for Company like this:
valuations = db.Valuations.Where(v => ((v.Creationdate >= startDate && v.Creationdate <= endDate) ||
v.SI47Instruction.Count(s => s.RequestDateTime >= startDate
&& s.RequestDateTime <= endDate) > 0))
.Include(t => t.SI47Instruction)
.Include(c => c.OriginationCompany)
.ToArray();
It will be eager loaded and you should be able to just do this when creating a new DashboardItem
Originator = item.OriginatorCompany.Name,
The scenario that I have so far is, I am fetching the logs from a device and storing it in the db sequentially with Checktype as I and O saying that his first entry was check-in and then check-out sequentially. This worked fine until I came up to an issue like;
Lets assume an emp has 3 logs in the device, 1 log for the date 15-feb-2018 and 2 logs on the date 16-feb-2018, what the query will do is it will insert the records as;
15-feb-2018 I
16-feb-2018 O
16-feb-2018 I
which is definitely wrong. it should be like
15-feb-2018 I
16-feb-2018 I
16-feb-2018 O
Current code snippet:
public static bool inn = true;
public ActionResult GetLogs()
{
if (isDevice2Connected)
{
//.. some code that fetches the logs
if (lstMachineInfo != null && lstMachineInfo.Count > 0)
{
var lastRecord = db.AttLogs.OrderByDescending(x => x.DateTime).FirstOrDefault();
List<Employee> empList = db.Emps.ToList();
var checkSingle = db.Perms.Where(x => x.Name == "Single" && x.IsPermitted == true).ToList();
if (lastRecord != null)
{
lstMachineInfo = lstMachineInfo.Where(x => x.DateTime > lastRecord.DateTime).ToList();
}
foreach(var emp in empList)
{
//this is where it should have some `Date` check
var empLogs = lstMachineInfo.Where(x => x.RegisterationId == int.Parse(emp.EnrollNumber)).ToList();
foreach (var p in empLogs)
{
if (checkSingle.Count > 0)
{
if (inn)
{
inn = false;
p.CheckType = "I";
}
else
{
inn = true;
p.CheckType = "O";
}
}
else
{
p.CheckType = "SINGLE DEVICE DEACTIVATED IN PERMISSIONS CHECK";
}
db.AttLogs.Add(p);
}
}
db.SaveChanges();
}
}
return View("GetAllUserInfo");
}
UPDATE:
trying to get the date from the empsLogs list so I can check if it has changed?
foreach (var p in empLogs)
{
if (checkSingle.Count > 0)
{
if (empLogs.Where(x => x.Date > NEXTDATEINLIST? ))
inn = true;
You're on the right track, all you need is to use p.Date instead of the variable and also a way to increment it like:
foreach(var emp in empList)
{
var empLogs = lstMachineInfo.Where(x => x.RegisterationId == int.Parse(emp.EnrollNumber)).ToList();
var prevDate = (from obj in empLogs select obj.Date).FirstOrDefault();
foreach (var p in empLogs)
{
if (checkSingle.Count > 0)
{
if (prevDate < p.Date) {
inn = true;
prevDate = p.Date;
}
if (inn)
{
inn = false;
p.CheckType = "I";
}
else
{
inn = true;
p.CheckType = "O";
}
}
else
{
p.CheckType = "SINGLE DEVICE DEACTIVATED IN PERMISSIONS CHECK";
}
db.AttendanceLogs.Add(p);
}
}
db.SaveChanges();
I have created a MySQL Database with a vast number of products and their cost. I utilize EF6 to wrap the database.
Based on the given input, I need to generate at random, a correct selection that meets the described criteria.
For example:
10 Items, Total Value $25
I am at a loss as how to properly go about iterating through the database to produce the required results.
What I am currently doing seems terribly inefficent:
using (var db = new Database())
{
var packageSelected = false;
var random = new Random();
var minItemId = (from d in db.products select d.id).Min();
var maxItemId = (from d in db.products select d.id).Max();
var timer = new Stopwatch();
timer.Start();
Console.WriteLine("Trying to make package...");
while (!packageSelected)
{
var currentItems = new List<int>();
for (var i = 0; i <= 9; i++)
{
var randomItem = random.Next(minItemId, maxItemId);
currentItems.Add(randomItem);
}
decimal? packageValue = 0;
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
{
var value = firstOrDefault.MSRP;
packageValue += value;
}
});
if (!(packageValue >= 25) || !(packageValue <= 26)) continue;
packageSelected = true;
timer.Stop();
Console.WriteLine("Took {0} seconds.", timer.Elapsed.TotalSeconds);
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
Console.WriteLine("Item: {0} - Price: ${1}", firstOrDefault.DESCRIPTION,
firstOrDefault.MSRP);
});
}
}
What about something like this:
public virtual TEntity GetRandom()
{
return DBSet.OrderBy(r => Guid.NewGuid()).Take(1).First();
}
public List<TEntity> Random(int amount, int maxprice)
{
var list = new List<TEntity>();
var tempPrice = 0;
for (int i = 0 ; i < amount; i++)
{
var element = GetRandom();
tempPrice += element.Price;
if (tempPrice > maxprice)
{
return list;
}
list.Add(element);
}
return list;
}
hope this helps
EDIT: If the maxprice is reached before the required amount of elements, the for-loop will stop and you won't get the full amount of elements.