I have another question that’s connected with my class:
public class Parent {
public IList<ParentDetail> ParentDetails {
get { return _ParentDetails; }
}
private List<ParentDetail> _ParentDetails = new List<ParentDetail>();
public Parent() {
this._ParentDetails = new List<ParentDetail>();
}
}
public class ParentDetail {
public int Id { get; set; }
}
}
Presently I iterate through ParentDetails and do some action for each ParentDetail. I am using MVC razor syntax so that’s the reason for the @( .. etc
@foreach (int index in Enumerable.Range(0, Model.Parent.ParentDetails.Count()))
{
Model.Parent.ParentDetails[@index].Id
This gives me the numbers 1,2,3 … etc IF the Ids have been assigned sequentially in the list with the first element having an Id of 1 and the second element having an Id of 2 etc.
However the Ids in my list are not assigned sequentially. I may have it like this:
list-element [0] has an Id of 3
list-element [1] has an Id of 4
list-element [2] has an Id of 1
list-element [3] has an Id of 2
What I need is something equivalent to the foreach that will let me iterate through my list based on the value of Id. Maybe I need to use the Index method to find but I don’t know how to put this all into a loop.
I know some C# but this is quite far beyond me. Can anyone help out with some ideas. I hope my question makes sense.
I will watch for comments so please just send a comment if there is something that’s not clear.
Thank you.
LINQ is the super easy solution for such cases:
You will need to add the
System.Linqnamespace with@using System.Linqif it’s not already included in your view.Aside
Your existing code does things in a kind of roundabout way though. This:
can also be written as
which is the natural way of iterating over a collection, and far more preferable (unless you also need the index of each
ParentDetailsobject in the collection).