在显示List位置时使用LINQ列出迭代

Emi*_*ily 4 c#

我刚刚问了一个关于我班级的问题:

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

}
Run Code Online (Sandbox Code Playgroud)

这里的一位专家(Jon)告诉我如何按照ParentDetails.Id的顺序迭代这个类.这是他的解决方案,运作良好. 上一个问题

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 ParentDetails where Id = details.ID
}
Run Code Online (Sandbox Code Playgroud)

我还需要在这个foreach中显示与Id对应的列表的索引值以及ParentDetail类中的一些其他数据.

因此,例如,它说//细节被处理,然后我希望能够打印出与foreach循环中当前Id相对应的索引值.

Tra*_*kel 6

使用第二个Enumerable.Select方法:

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);
} 
Run Code Online (Sandbox Code Playgroud)

这假设您希望索引按原始顺序排列.