Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to introduce Let keyword inside Linq statement with Group by

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
    };
like image 455
skjagini Avatar asked Apr 08 '11 14:04

skjagini


People also ask

What is the use of let keyword in LINQ?

The let keyword introduces a new range or local variable that can be used within a query using comprehension syntax.

How can we do a group by using LINQ query?

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.

What is the use of let keyword in C#?

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.

Can you use let in C#?

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.


1 Answers

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
};
like image 117
captncraig Avatar answered Nov 05 '22 17:11

captncraig