I have the following Linq statement with 'Group by' clause and would like to know how to introduce a let or any other statement to avoid repeating the sub query, lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First()
in the following example
var completionTimeModels =
from timeline in processTimelines
group timeline by timeline.LifecycleEventId into grouping
select new CompletionTimeViewModel()
{
// How to avoid repeating the same query to find the life cycle event?
Name = lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First().LifecycleEventName,
DisplayName = lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First().LifecycleEventDisplayName
};
The let keyword introduces a new range or local variable that can be used within a query using comprehension syntax.
Group by a range example The following example shows how to group source elements by using a numeric range as a group key. The query then projects the results into an anonymous type that contains only the first and last name and the percentile range to which the student belongs.
You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you supply. Once initialized with a value, the range variable cannot be used to store another value. However, if the range variable holds a queryable type, it can be queried.
We can also use the "Let" operator to store a calculated field within the Query. Using the "Let" Operator, we can create a variable in a query. This allows us to treat the result as a variable that we can then manipulate before getting the final result.
var completionTimeModels =
from timeline in processTimelines
group timeline by timeline.LifecycleEventId into grouping
let foo = lifecycleEvents.First(i => i.LifecycleEventId == grouping.Key)
select new CompletionTimeViewModel()
{
Name = foo.LifecycleEventName,
DisplayName = foo.LifecycleEventDisplayName
};
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