I'm trying to accomplish 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
});
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
Usually, an anonymous data type is used in the select clause of a LINQ expression to return a subset of properties from each object in the collection. In the following code example, we will see using an anonymous object in a LINQ query.
You create an anonymous type using the new operator with an object initializer syntax. The implicitly typed variable- var is used to hold the reference of anonymous types.
Anonymous types provide a convenient way to encapsulate a set of read-only properties in an object without having to explicitly define a type first. If you write a query that creates an object of an anonymous type in the select clause, the query returns an IEnumerable of the type.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With