My controller code is as follows
ViewBag.Districts = (from a in _dbContext.DISTRICTS
select new ComboItem {
ID = a.DISTRICT_ID,
Name = a.DISTRICT_NAME
}
).ToList();
My Razor View code as follows
#foreach (var dist in ViewBag.Districts)
{
if (item.DISTRICT_ID == dist.ID)
{
#dist.Name
}
}
Is there a way I can find item in ViewBag.Districts like ViewBag.Districts.where(m=>m.ID==item.DISTRICT_ID.
or linq expression so that i can avoid looping.
Anyone helps me greatly appreciated.
Viewbag is dynamic so compiler won't be able to identify its actual Type, so you need explicit type cast like this to work with Enumerable methods:-
((IEnumerable<ComboItem>)ViewBag.Districts).Where(x => x.ID == item.DISTRICT_ID);
I am assuming you want to use this in your View, Also the foreach loop you have posted won't work without explicit casting:-
#foreach (var dist in (IEnumerable<ComboItem>)ViewBag.Districts)
{
if (item.DISTRICT_ID == dist.ID)
{
#dist.Name
}
}
Related
This seems like it should be easy. Maybe it is and I'm just overthinking it. I have a bunch of items that have a category field set via a DropLink. I want to grab all of the items that match one of those options. E.g., Grab a list of all items where Category=Brochure. I can't seem to get the ID of the Droplink option to match against the Category option on the Item itself.
EDIT: Included current code by request.
public List<PoolDownload> Manuals
{
get
{
LookupField cat = (LookupField)this.Item.Fields["Category"];
return this.Downloads.Where(i => (i.Item.TemplateID == PoolDownload.TemplateId) &&
(i.Item.GlassCast<Pdp.Pool.Website.Business.Entities.PoolDownload>().Category.ToString() == cat.TargetID.ToString()))
.ToList();
}
}
I believe the problem is you're comparing a Guid.ToString() to a Sitecore.Data.ID.ToString(). These two statements return different values:
var guidToString = Sitecore.Context.Item.ID.Guid.ToString();
// "2a6a1d9a-be1d-411b-821a-7e63775280b3"
var idToString = Sitecore.Context.Item.ID.ToString();
// "{2A6A1D9A-BE1D-411B-821A-7E63775280B3}"
Cast the TargetID to a Guid as well and you should be good.
And to answer your question in your comment below about displaying the "Download Items" grouped by Category, you could use the GroupBy method, https://msdn.microsoft.com/en-us/library/bb534304(v=vs.110).aspx like this:
public IEnumerable<IGrouping<Guid, PoolDownload>> Manuals
{
get
{
LookupField cat = (LookupField)this.Item.Fields["Category"];
return this.Downloads.Where(i =>
i.Item.TemplateID == PoolDownload.TemplateId
&& i.Item.GlassCast<Pdp.Pool.Website.Business.Entities.PoolDownload>().Category.ToString() == cat.TargetID.Guid.ToString())
.GroupBy(i => i.Category);
}
}
And then, to loop over the results in the new Manuals property, you could do something like this:
foreach(var categoryGroup in Manuals)
{
var categoryGuid = categoryGroup.Key;
foreach(var download in categoryGroup)
{
var downloadInCurrentGroup = download.Item;
}
}
Newbie here, I have a list
#Model.Cleaners
If when going through the list
bool something = true
I want this item to move and now be the first item in the list (so it will show up first.)
I tried this
#foreach (var c in Model.Cleaners)
{
var item = c;
#Model.Cleaners.Remove(c);
#Model.Cleaners.Insert(0,item);
}
But I am getting an error Cannot convert type 'void' to object' What does that mean?
I don't know if there is an easier way to do it, but in the past when confronting this problem I did the following.
I added a nullable int to the database table, then I made a foreach loop and depending on whatever qualifications I wanted on top I gave a lower number. Then I did orderby.
The advantage of doing it like this is you have a lot of flexibility in your order. You can give 3 values 0, 1, and 2.
example
#foreach (var c in Model.Cleaners)
{
c.ConfirmationChecker = 1;
foreach (var p in c.TimeConfirmations)
{
if (condition)
{
c.ConfirmationChecker = 0;
}
}
}
Then afterwards you can do orderby
#foreach (var c in Model.Cleaners.OrderBy(x => x.ConfirmationChecker))
Hope this helps :)!
I have a user object that contains a nested list and i need to change the value of a element in the 3rd list and return the user object.
I want to do this with linq, below is the nested loop.
foreach (User itm in user)
{
if (itm.destinations!=null)
{
foreach (Models.Api.destinations.Destination dm in itm.destinations)
{
if (dm.destinationData != null)
{
foreach (Models.Api.destinations.DestinationData destData in dm.destinationData)
{
if (destData.type == "phone" & destData.data!="")
{
//i want to update the destData.data here .. something like
destData.data ='updated data';
}
}
}
}
}
}
I want the updated data to be available in the user object
can someone help me achieve this with the LINQ
Thanks in advance
Tarak
Try this:
foreach (var x in
(from itm in user
where itm.destinations!=null
from dm in itm.destinations
where dm.destinationData != null
from destData in dm.destinationData
where destData.type == "phone" & destData.data != ""
select new { itm, dm, destData }))
{
/* put your update code here. */
}
You didn't give us what the update code should look like or even the object models for us to work from.
Here is my code:
foreach (OrderItem item in OrderInfo.order)
{
orderItemViews.Single(i => i.numericUpDown.Name == item.id.ToString()).numericUpDown.Value = item.count;
}
It gives an exception.
I know that I can't change the collection inside foreach
How can I change this code to make it work? Best of all if it would be LINQ code.
exception says that "The collection was modified". sorry can't provide real message of exception because it in non-english
sorry guys. I've found where collection is changing. It was inside *numericUpDown_ValueChanged* handler. anyway I've got an answer. thank you
You can use ToList(), Like this :
foreach (OrderItem item in OrderInfo.order.ToList())
{
orderItemViews.Single(i => i.numericUpDown.Name == item.id.ToString()).numericUpDown.Value = item.count;
}
Or use normal for loop :
for (int i = 0 ; i < OrderInfo.order.Count; i++)
{
OrderItem item = OrderInfo.order[i];
orderItemViews.Single(i => i.numericUpDown.Name == item.id.ToString()).numericUpDown.Value = item.count;
}
Tip : Performance wise, It's better to use the second way.
This is what I do, when I need to modify the collection.
foreach (OrderItem item in OrderInfo.order.ToList())
{
...
}
Create a copy. Enumerate the copy, but update the original one.
You can use an extension ToEach static method:
public delegate void ToEachTransformAction<T>(ref T Telement);
[Extension()]
public static void ToEach<T>(Generic.IList<T> thislist, ToEachTransformAction<T> Transform)
{
for (var n = 0; n < thislist.Count; n++)
{
Transform.Invoke(thislist(n));
}
}
I have the following....
var jobsApplications = ( from applications in db.applications
where applications.employeeId == LogedUser.Id
select new { applications.id, applications.jobId, applications.confirmationDate });
Now I want to navigate this result like
foreach "something" in jobsApplications
But I don't now what to put in something since the select new create a new class.
Any suggestions
I guess you can let the compiler do the work for you:
foreach (var application in jobApplications)
{
// use the application wisely
}
Consider using Array.ForEach() to iterate through your IEnumerable or List. This is a bit more heavyweight.
Array.ForEach(jobsApplication, jobApp => {
if (jobApp.City == "Chicago")
{
jobApp.Approved = true;
}
});
If you want a simple foreach, then you can type the anonymous class as var
foreach (var jobApp in jobApplications)
{
if (jobApp.City == "Chicago")
{
jobApp.Approved = true;
}
}