开发者

Linq, use "variable" inside a anonymous type

I'm trying to accomplish开发者_StackOverflow中文版 something like this,

var data = from p in db.Projects
                   select new
                   {
                       Cost = p.CostReports.FirstOrDefault().Charged,
                       Tax = Cost * 0.25
                   };

In other words, I want to use Cost as a variable. Is it possible? If so, how?

My code is just an example, the project I'm working on is a bit more complicated.

Edit:

I hope this is a better example of what I'm trying to do,

var data = (from p in db.Projects
                    select new
                    {
                        Name = p.ProjectName,
                        Customer = p.CustomerID,
                        Cost = p.Cost
                    }).GroupBy(p => p.Customer)
                   .Select(g => new
                   {
                       Something = g.Where(p => p.Customer == g.Key).Sum(p => p.Cost),
                       SomethingElse = Something * 0.25
                   });


Use the let keyword in your query.

var data = from p in db.Projects 
           let cost = p.CostReports.FirstOrDefault().Charged
           select new 
           { 
              Cost = cost,
              Tax = cost * 0.25 
           }; 

Edit

Regarding your update and barring additional information, I might still be tempted to use let by rewriting your query structure.

var data = from g in db.Projects.Select(p => 
                new
                {
                    Name = p.ProjectName,
                    Customer = p.CustomerID,
                    Cost = p.Cost
                }
            ).GroupBy(p => p.Customer)
            let something = g.Sum(p => p.Cost)
            select new
            {
                Something = something,
                SomethingElse = something * 0.25
            };

In this case, from g in ... refers to the grouped data, which allows you to use query expression syntax against this data, including let.


var data = from p in db.Projects
           let cost = p.CostReports.FirstOrDefault().Charged
           select new
           {
               Cost = cost,
               Tax = cost * 0.25
           };


You could at least chain selects together and store your anonymous type as an intermediate result:

var data = (from p in db.Projects
               select new
               {
                   Cost = p.CostReports.FirstOrDefault().Charged,
                   Tax = Cost * 0.25
               })
           .select(anon => new { Cost = anon.Cost, Tax = anon.Cost * 0.25 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜