Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
              })
like image 468
okenshield Avatar asked Dec 16 '10 16:12

okenshield


1 Answers

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.

like image 78
Anthony Pegram Avatar answered Nov 15 '22 10:11

Anthony Pegram