okenshield
okenshield

Reputation: 565

Reference anonymous type properties

I am creating an composite anonymous type and wondered if I can reference the field YesPercent for the NoPercent?

 var test = (from p in db.users
             group p by p.ID into g
             select new
             {
                 ID = g.Key,
                 Frequency = g.Count(),
                 Question = g.FirstOrDefault().Question,
                 YesPercent = 50*564/32.5,
                 NoPercent = YesPercent - 10
              })

Upvotes: 6

Views: 209

Answers (1)

Anthony Pegram
Anthony Pegram

Reputation: 126992

Change it up a bit

 var test = (from p in db.users 
             group p by p.ID into g 
             let yesPercent = 50*564/32.5 // this variable will be available in your select 
             select new 
             { 
                 ID = g.Key, 
                 Frequency = g.Count(), 
                 Question = g.FirstOrDefault().Question, 
                 YesPercent = yesPercent, 
                 NoPercent = yesPercent - 10 
              }) 

I assume that you have something more complex actually happening. After all, the calculation for YesPercent has nothing to do with the queried data, so you could very well declare a variable outside of the query and use it inside.

Upvotes: 9

Related Questions