如何将数据重用到匿名类型声明中?

时间:2013-09-16 15:10:26

标签: c# .net linq anonymous-types

这是我的代码,我将匿名类型声明为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个数据重用到相同的匿名类型中。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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
            })