How can I add sequence IDs to classes in a list of another class?
I have the following class. Inside of the Parent class is a List of ParentDe开发者_如何学编程tail. Now I need to add a new field to the ParentDetail class. The field is called Id. What I need is a method in the main class that will iterate through the ParentDetails and populate the Id field with a number starting at 1.
Can anyone think of an easy way to do this? I am not sure how I can iterate through the List.
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; } <<<<<<<< new field
}
}
for(int i = 0; i < _ParentDetails.Count; i++)
{
_ParentDetails[i].Id = i + 1;
}
Could do a straight for(int i; i < Count; i++)
loop as suggested by Roy Dictus (+1 from me) - I'm just chucking this up there as an alternative, which is very useful in situations where you don't know the count of an enumerable.
foreach(var detail in _ParentDetails.
Select((d, i) => new { Item = d, Index = i + 1})
{
detail.Item.Id = detail.Index;
}
In your case you do; as you have an IList
, however.
精彩评论