LINQ adding to list object in loop - c#

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

Related

Compare list data with static string in C#

I have the following list,
String UpDownStatus = "UP";
List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.Date = (DateTime)reader["Date"];
newStock.High = (double)reader["High"];
newStock.Low = (double)reader["Low"];
newStock.Close = (double)reader["Close"];
newStock.Up_Down = (string)reader["Up_Down"];
StockData.Add(newStock);
The Up_Down column in my DB has the following two string : "UP" and "DOWN"
how can i compare whether the current value of
for (int i = 0; i < StockData.Count; i++)
{
if(StockData[i].Up_Down.CompareTo(UpDownStatus) != 0)
{
//do something
}
}
I know, i could reframe this statement like if (StockData[i].Up_Down=="UP") but i need a solution where I could use .CompareTo function.
If I understood your question right and you want to do something on all items which have the same up/down-status as the variable UpDownStatus, this would be the easiest way to do it:
foreach (var item in StockData.Where(e => e.Up_Down == UpDownStatus))
{
// do something
}

Foreach doesn't add each item from foreach to ViewModel

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

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.

Use LINQ to populate controls from object array

I am just trying to find a better way to populate some RadioButtonList controls. There are a set number of these on the usercontrol.ascx. The code is what I am currently using but I am still not very good with Linq and was wondering if there's a better way to do this.
quizId1 = quiz.Items[0].questionId;
pTag1.InnerText = quiz.Items[0].QuestionText;
foreach (Question q in quiz.Items[0].AnswerChoice)
{
radiobuttonlist1.Items.Add(new ListItem(q.Value, q.answerId));
}
same for radiobuttonlist2 but using Items[1] etc.
quizId2 = quiz.Items[1].questionId;
pTag2.InnerText = quiz.Items[1].QuestionText;
foreach (Question q in quiz.Items[1].AnswerChoice)
{
radiobuttonlist2.Items.Add(new ListItem(q.Value, q.answerId));
}
Sorry, the InnerText is a server side 'P' tag, pTag1, pTag2 etc.
Try this
var listItems = (from x in quiz.Items[0].AnswerChoice
select new ListItem { Text = q.Value, Value = q.answerId }
).ToList<ListItem>();
radiobuttonlist1.DataSource = listItems;
radiobuttonlist1.DataBind();
I suppose you could do something like this:
var listItems = from q in quiz.Items[0].AnswerChoice
select new ListItem(q.Value, q.answerId);
radioButtonlist1.Items.AddRange(listItems.ToArray());
though I'm not really sure if that buys you anything other than experience with LINQ...
I assume you want to use ling to popiulate several controls, not an individual control.
Linq is for querying, not updating. To update you still need either for or foreach loops.
If your RadioButtonList objects are in a collection, you could just loop over them:
var radioList = new [] {radiobuttonlist1, radiobuttonlist2, ...};
for(int i = 0; i < quiz.Items.Length; i++)
{
var quizId = quiz.Items[i].questionId;
radioList[i].InnerText = quiz.Items[i].QuestionText;
radioList[i].Items.AddRange(quiz.Items[i]
.AnswerChoice
.Select(q => => new ListItem(q.Value, q.answerId))
.ToArray()
);
}
or use DataSource as others have suggested:
var radioList = new [] {radiobuttonlist1, radiobuttonlist2, ...};
for(int i = 0; i < quiz.Items.Length; i++)
{
var quizId = quiz.Items[i].questionId;
radioList[i].InnerText = quiz.Items[i].QuestionText;
radioList[i].DataSource = quiz.Items[i].AnswerChoice;
radioList[i].DataTextField = "Value";
radioList[i].DataValueField = "answerId";
}
but there's no Linq way to populate several controls.

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.

Categories