Foreach doesn't add each item from foreach to ViewModel - c#

I am sure I am just thinking about this far too much, but I am trying to get a list and everything works except for one thing. And I know why it's doing it, it's getting the last item of the foreach that is assigned to the outside of the loop and returning just that one item. But I want to to return ALL of them.
What am I doing wrong?
var cheeses = _repository.GetAllYearSetupIds();
var gouda = new CollectionsManagementViewModel();
var yearSetupId = 0;
foreach(var cheddar in cheeses)
{
yearSetupId = cheddar.YearSetupId;
gouda = _repository.GetOverdueBalances(page, pageLength, yearSetupId, balancefilter, sort, direction == Constants.ascending, spreadsheetType);
gouda.Title = title + " Management";
}
return View("CollectionsManagement", gouda);

Currently, you are updating single instance of CollectionsManagementViewModel named gouda on each iteration in your loop. After the loop gouda will have the value from the last iteration.
You should create new instance of CollectionsManagementViewModel on each iteration and add this instance to the list of view models. Of course naming should be meaningful:
// list of models, because you want ALL of them
var managementModels = new List<CollectionsManagementViewModel>();
var setupIds = _repository.GetAllYearSetupIds();
foreach(var setupId in setupIds)
{
// new model created for each setup id
var managementModel = _repository.GetOverdueBalances(page, pageLength,
setupId.YearSetupId, balancefilter,
sort, direction == Constants.ascending,
spreadsheetType);
managementModel.Title = title + " Management";
managementModels.Add(managementModel); // add model to list
}
// pass collection to view
return View("CollectionsManagement", managementModels);

Hi Hope following code may helpful for you
var cheeses = _repository.GetAllYearSetupIds();
var lstgouda = new List<CollectionsManagementViewModel>(); //make a list
var yearSetupId = 0;
foreach(var cheddar in cheeses)
{
var gouda = new CollectionsManagementViewModel();
yearSetupId = cheddar.YearSetupId;
gouda = _repository.GetOverdueBalances(page, pageLength, yearSetupId, balancefilter, sort, direction == Constants.ascending, spreadsheetType);
gouda.Title = title + " Management";
lstgouda.add(gouda); //add it to list
}
return View("CollectionsManagement", lstgouda);
Thanks
Karthik

Related

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 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.

Filtering a List with an array items

i need to filter a list with strings in an array. Below code doesn't return the expected result.
List<searchModel> obj=//datasource is assigned from database
mystring="city1,city2";
string[] subs = mystring.Split(',');
foreach (string item in subs)
{
obj = obj.Where(o => o.property.city.ToLower().Contains(item)).ToList();
}
As far as you're using Contains, I'd say you could be trying to get
entries, city of which matches any city from mystring
entries, city of which match all cities from mystring
So, having (I simplified searchModel class, having omitted property):
List<searchModel> obj = new List<searchModel>
{
new searchModel{city = "city1"},
new searchModel{city = "city2"},
new searchModel{city = "city3"}
};
var mystring = "city1,city2";
var subs = mystring.Split(',').ToList(); //let it be also List<T>
We can do:
//the 1st option
var orFilter = obj.Where(o => subs.Any(s => o.city.ToLower().Contains(s)))
.ToList();
//the 2nd option
var andFilter = obj.Where(o => subs.TrueForAll(s => o.city.ToLower().Contains(s)))
.ToList();
Then do a simple check
foreach (var o in andFilter)
{
Console.WriteLine(o.city);
}
I'd say that the OP is equal to option 2, not option 1.
I think you want this, or something close - I haven't tested it:
List<searchModel> obj=//datasource is assigned from database
mystring="city1,city2";
string[] subs = mystring.Split(',');
obj = obj.Where(o => subs.Contains(o.property.city.ToLower())).ToList();
What you're currently doing is filtering the list by ALL cities. So you'll only return results where o.property.city equals "city1" and "city2" (and any other cities you might have in the list). So you won't get any results.
To match any city in the list instead, try this:
var myFilteredObj = obj.Where(o => subs.Contains(o.property.city.ToLower()).ToList();
I add this codes of lines, probably will help someone and maybe someone will optimize it:
var jaggedArray = new string[100][];
var i = 0;
jaggedArray[i] = {"first folder","first file","first 5 files","last 5 folder"};
filter = "irs le";
var arrFilters = filter.Split(' ');
foreach (var arrFilter in arrFilters)
{
jaggedArray[i] = jaggedArray[i].Where(p =>p.ToLower().Contains(arrFilter.ToLower())).ToArray();
jaggedArray[i + 1] = jaggedArray[i];
i++;
}
return jaggedArray[i]; //new array after filter
//result: "first file","first 5 files"
var result = obj.Where(piD => subs.Contains(piD.city)).ToList();
The code above will filter the obj List based on the string array.

Strange values in an array - after I change them they remain the same

Here is my code:
var items = tableInDatabase.All("WHERE [Order] > " + order);
foreach (var i in items.ToArray())
{
i.Order = 7;
}
tableInDatabase.Save(items.ToArray());
However, when the breakpoint comes to the last line (after the foreach loop), every element of items has an order the same as before (not 7). Why is this happening?
While still in the loop, i has an order of 7.
I'm using Massive, and this is the example from its official page:
var table = new Products();
var drinks = table.All("WHERE CategoryID = 8");
foreach(var item in drinks.ToArray()){
item.CategoryID = 12;
}
table.Save(drinks.ToArray());
I also tried:
foreach (var i in items.ToArray())
{
tableInDatabase.Update(i, i.Id);
}
And nothing.
The return type od tableInDatabase is the class TableInDatabase. This is the definition:
public TableInDatabase() : base(connectionString, "System.Data.SqlClient", "TableInDatabase", "Id") { }
use this code:
var items = tableInDatabase.All("WHERE [Order] > " + order);
var array = items.ToArray();
foreach (var i in array)
{
i.Order = 7;
}
tableInDatabase.Save(array);
ToArray() creates a new copy as said by Romil, In your case since you are using Massive, you can probably do what Adam has said, but that option creates two variable. You can try the following.
var items = tableInDatabase.All("WHERE [Order] > " + order).ToArray();
foreach (var i in items)
{
i.Order = 7;
}
tableInDatabase.Save(items);
This is a known issue with Massive example and has been reported here

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