Pergunta

This is my code where I declare a anonymous type into a 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();

If you look the line where I added //IMPOSSIBLE, I try to reuse 2 data just calculated above into the same anonymous type.

How can I achieve this?

Foi útil?

Solução 2

You can do it by adding a second level of 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
            })

Outras dicas

You would have to create an intermediate object which you can then reference the values of.

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();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top