包裹是清单

每个包裹都有Owners属性,其中包含List

parcels.Where(p => !p.Owners.IsNullOrEmpty()).SelectMany(p => p.Owners)
                    .OrderByDescending(x => x.RecordingDate ?? x.SaleDate ?? x.DateEntered)
                    .ForEach(owner =>
                    {
                    /* HERE I need to access to p which was a parent of this Owner */
                    }


不确定如何重写...

最佳答案

进行匿名配对以进行迭代。

 foreach(var pair in parcels
    .Where(p => p.Owners != null)
    .SelectMany(p => new { o = p.Owners, p })
    .OrderByDescending(x => x.o.RecordingDate ?? x.o.SaleDate ?? x.o.DateEntered)) {

    var owner = pair.o;
    var parcel = pair.p;

    // do stuff
 }
 // alternate syntax
 foreach(var pair in from p in parcels
                     where p.Owners != null
                     from o in p.Owners
                     orderby o.RecordingDate ?? o.SaleDate ?? o.DateEntered descending
                     select new { o, p }) {
     var owner  = pair.o;
     var parcel = pair.p;
     // do stuff
 }

关于c# - 如何使用LINQ.FOREACH访问父级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4695064/

10-11 05:59