1

这是我的代码,我将匿名类型声明为select

var projectsByManagersAndMonths = projectDates
    .Where(pd => pd.project.isEnabled)
    .GroupBy(pd => new { pd.project.manager, pd.project.dtEnd.Value.Month })
    .Select(group => new
        {
            Manager = group.Key.manager.displayName,
            Month = group.Key.Month,
            Projects = group.Select(pd => new 
                { 
                    Count = group.Count(),
                    CostToComplete = group.Sum(pdd => pdd.totals.costToComplete),
                    TimeWorkable = new UserBillingRate(WS, group.Key.manager, new Period(start, end)).TimeWorkable,
                    StatusOfCharge = CostToComplete / TimeWorkable //IMPOSSIBLE
                })
        })
    .ToList();

如果您查看我添加的行//IMPOSSIBLE,我会尝试将上面刚刚计算的 2 个数据重用到相同的匿名类型中。

我怎样才能做到这一点?

4

2 回答 2

3

您必须创建一个中间对象,然后您可以引用其值。

var projectsByManagersAndMonths = projectDates
    .Where(pd => pd.project.isEnabled)
    .GroupBy(pd => new { pd.project.manager, pd.project.dtEnd.Value.Month })
    .Select(group => new
        {
            Manager = group.Key.manager.displayName,
            Month = group.Key.Month,
            Projects = group.Select(pd => new 
                { 
                    Count = group.Count(),
                    CostToComplete = group.Sum(pdd => pdd.totals.costToComplete),
                    TimeWorkable = new UserBillingRate(WS, group.Key.manager, new Period(start, end)).TimeWorkable,
                }).Select(pd => new 
                { 
                    Count = pd.Count,
                    CostToComplete = pd.CostToComplete,
                    TimeWorkable = pd.TimeWorkable,
                    StatusOfCharge = pd.CostToComplete / pd.TimeWorkable //POSSIBLE
                })
        })
    .ToList();
于 2013-09-16T15:14:18.943 回答
2

您可以通过添加第二级来做到这一点Select

Projects = group.Select(pd => new 
            { // This level deals with the first level of computation
                Count = group.Count(),
                CostToComplete = group.Sum(pdd => pdd.totals.costToComplete),
                TimeWorkable = new UserBillingRate(WS, group.Key.manager, new Period(start, end)).TimeWorkable
              // This level takes the computed results, and add derived computations
            }).Select(pd => new {
                pd.Count,
                pd.CostToComplete,
                pd.TimeWorkable,
              // Now that pd is an anonymous class created by the level above,
              // both pd.CostToComplete and pd.TimeWorkable are defined.
                StatusOfCharge = pd.CostToComplete / pd.TimeWorkable
            })
于 2013-09-16T15:14:53.593 回答