Nested For-each Loop Sequence issue with values - c#

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);
}

Related

How convert IQueryable to list for showing return data?

I have a variable which is IQueryable and I have parameter in my viewmodel that it shows a differences between my selected day and today the code is:
public async Task<ResultData<HomePlannedRecieptInfo>> GetHomePlannedReciepts(HomePlannedRecieptQuery query)
{
var datelist = new List<DateTime>();
var date = DateTime.Now;
for (var i = 0; i <= 6; i++)
{
datelist.Add(date.AddDays(i));
}
datelist.Add(date);
IQueryable<HomePlannedRecieptInfo> result = context.HomePlannedRecieptInfos.Where(t=>t.Date >= DateTime.Today);
foreach (var item in result.ToList())
{
item.DayDiff = (item.Date.Date - DateTime.Now.Date).TotalDays.ToString();
}
var offset = (query.PageNumber - 1) * query.PageSize;
var psize = query.PageSize;
var countQuery = await result.CountAsync();
var data = result.OrderByDescending(c => c.Date);
return new ResultData<HomePlannedRecieptInfo>
{
CurrentPage = query.PageNumber,
TotalItems = countQuery,
PageSize = query.PageSize,
Data = data.ToList()
};
when I execute the code in foreach I can see the number of days in item.dayDiff but I can't see it when the the data return. Can somebody help me please?
You're calling result.ToList(), but you're just iterating over it in the foreach loop, you're not actually storing it anywhere. This should fix it:
var resultAsList = result.ToList();
foreach (var item in resultAsList)
{
item.DayDiff = (item.Date.Date - DateTime.Now.Date).TotalDays.ToString();
}
...
var data = resultAsList.OrderByDescending(c => c.Date);
That is because every time you materialize a IQueryable the data is taken from the database. You materializing twice in your code. Once in the foreach and once when returning the data in data.ToList(). Hence you have two lists with different items. Since you are changing the data in the first list the second will not receive that data.
You have two possibilities:
Call ToList before the foreach and use the same materialized list for changing the property and returning the same list
Change the get acessor for DayDiff to following public string DayDiff {get => (Date.Date - DateTime.Now.Date).TotalDays.ToString();} Using this has the advantage that you do not have to remind you to set the DayDiff if you query the data on other locations of your code

How to fix extra run in loop?

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;
}

Get listitems according to the index of another list

I have a List<List<string>> with three nested lists. Now I need to check if List[1] equals a certain string and if so, check if the value at this index in List[2] has another certain string. If both conditions return true, then I need to get that certain index and get the item of List[0].
For example:
var list = Titles[0];
var list2 = Titles[1];
var list3 = Titles[2];
foreach (var item in list2)
{
if (item.Contains("Dt."))
{
int idx = list2.IndexOf(item);
var value = list3.ElementAt(idx);
if (value.Contains("25.04.2017"))
{
var newList = list.ElementAt(idx);
}
}
}
This approach doesn't seem very efficient in regards to performance, especially if the nested list contains ~9000 items.
I tried to get the result via lambda expressions first, but I'm not sure if this is the right approach either.
What would be the best or most efficient solution?
Eliminate ElementAt with direct access to index. I believe ElementAt iterates over List in order to get i'th element
Eliminate usage of IndexOf with index provided by for loop I believe IndexOf iterates over List in order to find matching element.
var list = Titles[0];
var list2 = Titles[1];
var list3 = Titles[2];
for (int i = 0 ; i < list2.Count; ++ i)
{
var item = list2[i];
if (item.Contains("Dt."))
{
var value = list3[i];
if (value.Contains("25.04.2017"))
{
var newList = list[i];
}
}
}
Note if size of list2 is greater than size of list or list3 then you potentially get IndexOutOfRangeException
Lambda equivalent for your code:
if(list2.Any(item => item.Contains("Dt.")))
{
int idx = list2.IndexOf("Dt.");
if(list3.ElementAt(idx).Contains("25.04.2017"))
{
var newList = list.ElementAt(idx);
}
}
for (int i = 0; i < list2.Count; ++i)
{
var item = list2[i];
if (item.Contains("Dt."))
{
var value = list3[i];
if (value.Contains("25.04.2017"))
{
var newList = list[i];
break; // Break the loop :-)
}
}
}

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.

LINQ adding to list object in loop

I have a situation where I need to populate a list object by looping through a loop of objects, check against a condition, and if the condition is met, add the item to my list. Currently I cannot find an example of the syntax required to add to the list rather than clear it and repopulate it each time the loop iterates to the next item. Can somebody help?
List<ProfileRightsJSON> prf = new List<ProfileRightsJSON>();
try
{
for (int i = 0; i < lstProfiles.Count; i++)
{
prf = (from p in _database.tblProfileRights
where p.fkProfileID ==
lstProfiles[i].ProfileID
select new ProfileRightsJSON
{
FunctionID = p.fkFunctionID,
UserTypeID = p.fkUserTypeID,
RecursiveRights = p.RecursiveRights
}).ToList();
}
It looks like you really want something like this:
var profileIds = lstProfiles.Select(x => x.ProfileID).ToList();
var prf = (from p in _database.tblProfileRights
where profileIds.Contains(p.fkProfileID)
select new ProfileRightsJSON
{
FunctionID = p.fkFunctionID,
UserTypeID = p.fkUserTypeID,
RecursiveRights = p.RecursiveRights
}).ToList();

Categories