How to fix extra run in loop? - c#

I create an object in which values from 3 rows and I need to loop through 3 lines and add values from this object (rowsCmd).
private void CalculateDist()
{
var Unique= Cursor.GetFieldValue<int>("Unique");
var document = new HeadersRepository().Get(Unique);
if (document == null)
{
return;
}
var rowsRepository = new RowsRepository(document);
var rowList = rowsRepository.GetRows();
var cmd = SqlClient.Main.CreateCommand(string.Format(
#"select DOC.Unique, DOC.Number from DOC where DOC.Unique =#Unique order by DOC.Number"), new { Unique });
var rowsCmd = cmd.ExecObjects(new
{
Unique= 0,
Number= 0,
});
foreach (var row in rowList)
{
foreach (var rowCmd in rowsCmd)
{
row.Number = rowCmd.Number;
row.Number= rowCmd.Number;
}
}
}
if i have 2 rows this code will execute 4 time, but need only 2. how to make a loop which will pass through each rows in my list rowList and put data from object rowsCmd in 1 loop

Your code always set row values with rowsCmd list's last element. So it is a wrong code segment.
For your purpose you can use for loop instead of foreach loop.
for(int i=0; i< rowList.Count; i++){
rowList[i].Number = rowsCmd[i].Number;
}

Related

Add values to a list within a foreach loop

I simply wanted to add float values to list within a foreach loop. The code perfectly reads row.Size as well as row.Price and adds additional RData1 sets to InDat, but uses always the "latest" dataset of RData1.Size and RData1.Price instead of keeping the "previous" loop values. So after closing the loop, I get the same values in each line of the list.
IEnumerable<ModelInput> inputData = mlC.Data.CreateEnumerable<ModelInput>(tView,reuseRowObject: true);
public List<InputData> InDat { get; set; }
InDat = new List<InputData>();
InputData RData1 = new InputData();
int count = 0;
foreach (ModelInput row in inputData)
{
count++;
RData1.Size = Convert.ToString(row.Size);
RData1.Price = Convert.ToString(row.Price);
InDat.Add(RData1);
}
You need to instantiate Rdatat1 inside the loop:
int count = 0;
foreach (ModelInput row in inputData)
{
count++;
InputData RData1 = new InputData();
RData1.Size = Convert.ToString(row.Size);
RData1.Price = Convert.ToString(row.Price);
InDat.Add(RData1);
}

Nested For-each Loop Sequence issue with values

var TeamLeadAuditsAndQuality = unitofwork.AuditNewRepository.SQLQuery<SPTotalAuditAndQualityOfOfMonthByTeamLead_Result>("SPTotalAuditAndQualityOfOfMonthByTeamLead").ToList();
var TeamLeadFeedBacks = unitofwork.AuditNewRepository.SQLQuery<SPTotalFeedBackOfOfMonthByTeamLead_Result>("SPTotalFeedBackOfOfMonthByTeamLead").ToList();
foreach (var items in TeamLeadAuditsAndQuality)
{
TeamLeadMonthlyResult Result = new TeamLeadMonthlyResult();
Result.TeamLead = items.TeamLead;
Result.MonthlyAudits = Convert.ToInt32(items.TotalAuditsOfCRU);
Result.MonthlyQuality = items.Average;
foreach (var item in TeamLeadFeedBacks)
{
Result.MonthlyFeedbacks = Convert.ToInt32(item.TotalFeedbackOfCRU);
}
List.Add(Result);
}
model.TeamLeadMonthlyResultVMList = List;
return View(model);
}
`````````````````````````````````````````````
The Above is my Code and i am getting data from stored procedure and for this i am using for each loop to iterate data but there is one issue that is i want to get the data in sequence that 1st row of 1st list and 1st row of second list and 2nd for 2nd n so on but i m getting the result in format that second list iterate fully and i got the same ans in whole column like this
output image is here
the red column is repeating because 2nd foreach loop iterate fully and get the same ans i want to restrict it and get the ans in sequence please help me how will i do that
Use for loop.
var TeamLeadAuditsAndQuality =unitofwork.AuditNewRepository.SQLQuery<SPTotalAuditAndQualityOfOfMonthByTeamLead_Result>("SPTotalAuditAndQualityOfOfMonthByTeamLead").ToList();
var TeamLeadFeedBacks = unitofwork.AuditNewRepository.SQLQuery<SPTotalFeedBackOfOfMonthByTeamLead_Result>("SPTotalFeedBackOfOfMonthByTeamLead").ToList();
for(var i=0 ;i < TeamLeadAuditsAndQuality.Count; i++)
{
TeamLeadMonthlyResult Result = new TeamLeadMonthlyResult();
Result.TeamLead = TeamLeadAuditsAndQuality[i].TeamLead;
Result.MonthlyAudits = Convert.ToInt32(TeamLeadAuditsAndQuality[i].TotalAuditsOfCRU);
Result.MonthlyQuality = TeamLeadAuditsAndQuality[i].Average;
if(i<= TeamLeadFeedBacks.Count)
Result.MonthlyFeedbacks = Convert.ToInt32(TeamLeadFeedBacks[i].TotalFeedbackOfCRU);
List.Add(Result);
}
model.TeamLeadMonthlyResultVMList = List;
return View(model);
}

How do i add data to a specific column in datagridview?

I have i already made 3 lists of elements that i want to insert on my datagridview,
but the problem is when i try to insert data on my datagrid a receive something like this,
so to insert data i used the following code:
IList<string> ruas = new List<string>();
foreach (var element in Gdriver.FindElements(By.ClassName("search-title")))
{
//ruas.Add(element.Text);
table.Rows.Add(element.Text);
}
IList<string> codps = new List<string>();
foreach(var Codpelement in Gdriver.FindElements(By.ClassName("cp")))
{
table.Rows.Add("",Codpelement.Text);
}
IList<string> Distritos = new List<string>();
foreach (var Distritoelement in Gdriver.FindElements(By.ClassName("local")))
{
//Distritos.Add(Distritoelement.Text);
table.Rows.Add("","",Distritoelement.Text.Substring(Distritoelement.Text.LastIndexOf(',') + 1));
}
Could you kindly, tell me a better way to make the data appear from top to bottom?
Thanks.
The problem is that you enter a single value per row. You should have three rows in total, but you have 3 * numberofcolumns rows. Instead of your current approach I recommend the following:
IList<string> ruas = new List<string>();
foreach (var element in Gdriver.FindElements(By.ClassName("search-title")))
{
ruas.Add(element.Text);
}
IList<string> codps = new List<string>();
foreach(var Codpelement in Gdriver.FindElements(By.ClassName("cp")))
{
codps.Add(Codpelement.Text);
}
IList<string> Distritos = new List<string>();
foreach (var Distritoelement in Gdriver.FindElements(By.ClassName("local")))
{
Distritos.Add(Distritoelement.Text.Substring(Distritoelement.Text.LastIndexOf(',') + 1));
}
for (int i = 0; i < ruas.Count; i++) {
table.Rows.Add(ruas.ElementAt(i), codps.ElementAt(i), Distritos.ElementAt(i));
}

How i foreach loop in listitems values entity framework

I have 2 lists. One has 3 records like 1 , 2 , 3 and seconds list holds table records. All i wanna do add first list values to second list.
I hope helps.
foreach (var itemAgent in listofValues)
{
foreach (var item in formSorgu)
{
#region MyRegion
CrmDonusleri crmEkleme = new CrmDonusleri()
{
AradigiBolge = item.bolge,
AramaTarihi = Convert.ToDateTime(item.aratarihi),
Musno = item.musno,
GeriDonusYapildiMi = false,
AtanmaTarihi = DateTime.Now,
KanalAdi = item.kanal,
ProgramAdi = item.program,
AtananAgent = itemAgent
};
DbContext.CrmDonusleri.Add(crmEkleme);
#endregion
}
}
DbContext.SaveChanges();
listofValues hold 3 records and formSorgu hold 2000 records. listofValues as List One and formSorgu as List Two. And i want my final list like Picture below.
I don't think my code is right. Please show me the right way to write this query.
for (int i = formSorgu.Count + 1; i >= 0; i--)
{
foreach (var itemAgent in listofValues)
{
CrmDonusleri crmEkkle = new CrmDonusleri()
{
Musno = formSorgu.FirstOrDefault().musno,
AtananAgent = itemAgent
};
}
}
when i use this code it gets one record from formSorgu but add to listofValues 3 times i just want it to foreach one time and go out from foreach loop and carry on other for loop record.
actually, i love to share i am not like stackover mods. so i found an excellent answer on internet. you can find a link that equally selecting items from list and psuedo run.
solution link
that is a link i used. and i turn my code like this;
var randoAgent = new RandomPicker<string>(listofValues);
foreach (var itemSorgu in formSorgu)
{
var item = randoAgent.PickItem();
CrmDonusleri crmEkle = new CrmDonusleri()
{
Musno = itemSorgu.musno,
TelNo = itemSorgu.telno,
AtananAgent = item,
AradigiBolge = itemSorgu.bolge,
AramaTarihi = Convert.ToDateTime(itemSorgu.aratarihi),
AtanmaTarihi = DateTime.Now,
Ekleyen = itemSorgu.ekleyen,
GeriDonusYapildiMi = false,
KanalAdi = itemSorgu.kanal,
ProgramAdi = itemSorgu.program
};
DbContext.CrmDonusleri.Add(crmEkle);
}
DbContext.SaveChanges();
and works perfect.

Taking a set of items from a list and to perform some operation based on need

I have a list of items in a list. From that list I need to take the first 1000 items and need to submit the package and then again I need to take another 1000 and need to submit a package. If the list is not having 1000 I need to submit the package with all the items. for that I wrote the following code which is returning an error as collection modified.
List<SyncQueue> tempMassiveSyncQueue=massiveSyncQueue;
while (tempMassiveSyncQueue.Count != 0)
{
int MassivePackageFileCount =Convert.ToInt32(ConfigurationManager.AppSettings["MassivePackageFileLimit"]);
massiveSyncQueues = tempMassiveSyncQueue;
List<SyncQueue> tempMassivePackageSyncQueue=new List<SyncQueue>();
if (massiveSyncQueues.Count > 1000
{
var massivePackageSyncQueue = (massiveSyncQueues.Take(1000)).ToList<SyncQueue>();
tempMassivePackageSyncQueue = massivePackageSyncQueue;
SubmitPackage(massivePackageSyncQueue);
}
if (tempMassivePackageSyncQueue.Count != 0)
{
foreach (var massivesynq in tempMassiveSyncQueue)
{
foreach (var deleteId in tempMassivePackageSyncQueue.Where(id => id.SyncQueueId == massivesynq.SyncQueueId))
{
tempMassiveSyncQueue.Remove(massivesynq);
}
}
}
else
{
SubmitPackage(massiveSyncQueues);
}
massiveSyncQueues = null;
}
Can any one help on this?
Incorporate Skip into your logic
int loopCount = 0;
While(true)
{
var ListToProcess = massiveSyncQueue.Skip(loopCount*1000).Take(1000);
SubmitPackage(ListToProcess);
if(ListToProcess.Count < 1000) // We know there are no more in the list massive list.
{
break;
}
loopCnt++;
}
Your problem is that you are adjusting the collection on which the bounds of the foreach construct are set.
Try using ToList() on the collection you are looping through, as this creates a new List in memory:
foreach (var massivesynq in tempMassiveSyncQueue.ToList())
{
foreach (var deleteId in tempMassivePackageSyncQueue.Where(id => id.SyncQueueId == massivesynq.SyncQueueId).ToList())
{
tempMassiveSyncQueue.Remove(massivesynq);
}
}
In line 1 you set tempMassiveSyncQueue = massiveSyncQueue, yet within the while loop you set massiveSyncQueue = tempMassiveSync.
The collection modified error usually occurs when you modify the collection you are looping through. Which is why you need to first create a copy of the collection which is INDEPENDANT to the original collection and loop through that.
Before the while loop you need to add all items in massiveSyncQueue to tempMassiveSyncQueue. You then need to loop through the temp list with your code. In the second loop, you are removing items from the list you are looping through. I assume you meant to remove the items from massiveSyncQueue and not the temp list.
Try the following:
List<SyncQueue> tempMassiveSyncQueue = new List<SyncQueue>();
foreach(var item in massiveSyncQueue)
{
tempMassiveSyncQueue.Add(item);
}
while (tempMassiveSyncQueue.Count != 0)
{
int MassivePackageFileCount = Convert.ToInt32(ConfigurationManager.AppSettings["MassivePackageFileLimit"]);
List<SyncQueue> tempMassivePackageSyncQueue=new List<SyncQueue>();
if (massiveSyncQueues.Count > 1000
{
var massivePackageSyncQueue = (massiveSyncQueues.Take(1000)).ToList<SyncQueue>();
tempMassivePackageSyncQueue = massivePackageSyncQueue;
SubmitPackage(massivePackageSyncQueue);
}
if (tempMassivePackageSyncQueue.Count != 0)
{
foreach (var massivesynq in massiveSyncQueue)
{
foreach (var deleteId in tempMassivePackageSyncQueue.Where(id => id.SyncQueueId == massivesynq.SyncQueueId))
{
massiveSyncQueue.Remove(massivesynq);
}
}
}
else
{
SubmitPackage(massiveSyncQueues);
}
massiveSyncQueues = null;
}
Try this
int count=1;
while(tempMassivePackageSyncQueue.Count>1000)
{
var massivePackageSyncQueue = (massiveSyncQueues.skip(count*1000).Take(1000)).ToList<SyncQueue>();
tempMassivePackageSyncQueue = massivePackageSyncQueue;
SubmitPackage(massivePackageSyncQueue);
count++;
}
var massivePackageSyncQueue = (massiveSyncQueues.skip(count*1000).Take()).ToList<SyncQueue>();
tempMassivePackageSyncQueue = massivePackageSyncQueue;
SubmitPackage(massivePackageSyncQueue);

Categories