List iteration using LINQ while showing the List position
I just asked a question about 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; }
}
}
One of the experts here (Jon) told me how I could iterate through this class in order of the ParentDetails.Id. Here's his solution which works good. Previous question
foreach(var details in Model.Parent.ParentDetails.OrderBy(d => d.Id))
{
// details are processed in increasing order of Id here
// what's needed is to get access to the original order
// information. Something like as follows:
// select index position from Paren开发者_JS百科tDetails where Id = details.ID
}
What I also need is within this foreach to show the index value of the list corresponding to the Id along with some other data that's in the ParentDetail class.
So for example where it says // details are processed then I want to be able to print out the index value that corresponded to the current Id in the foreach loop.
Use the second Enumerable.Select method:
foreach(var details in Model.Parent.ParentDetails
.Select((value, idx) => new { Index = idx, Value = value })
.OrderBy(d => d.Value.Id)
)
{
// details are processed in increasing order of Id here
Console.WriteLine("{0}: {1}", details.Index, details.Value);
}
This is assuming you wanted the indices to be in the original order.
You can use a regular for
for that.
var ordered = Model.Parent.ParentDetails.OrderBy(d => d.Id).ToList();
for(int i = 0; i < ordered.Count; i++)
{
// details are processed in increasing order of Id here
}
精彩评论