Iterating a List Using LINQ, Showing 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 (John) told me how I can go through this class in order in ParentDetails.Id. Here is his solution that works well. Previous question

 foreach(var details in Model.Parent.ParentDetails.OrderBy(d => d.Id)) { // details are processed in increasing order of Id here // what needed is to get access to the original order // information. Something like as follows: // select index position from ParentDetails where Id = details.ID } 

What I also need is inside this foreach to show the index value of the list corresponding to Id along with some other data that is in the ParentDetail class.

So, for example, when he says that the details are being processed, I want to be able to print the index value corresponding to the current identifier in the foreach loop.

+4
source share
2 answers

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

The indices are supposed to be in the original order.

+6
source

For this you can use regular for .

 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 } 
+1
source

All Articles