skjagini
skjagini

Reputation: 3217

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
    };

Upvotes: 7

Views: 11404

Answers (4)

captncraig
captncraig

Reputation: 23118

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
};

Upvotes: 9

abatishchev
abatishchev

Reputation: 100358

var completionTimeModels =
    from timeline in processTimelines 
    group timeline by timeline.LifecycleEventId into grouping
    let lifecyleEvent = lifecycleEvents.First(i => i.LifecycleEventId == grouping.Key)
    select new CompletionTimeViewModel()
    {
        // How to avoid repeating the same query to find the life cycle event?
        Name = lifecyleEvent.LifecycleEventName
        DisplayName = lifecyleEvent.LifecycleEventDisplayName
    };

Upvotes: 1

phoog
phoog

Reputation: 43056

var completionTimeModels =
    from timeline in processTimelines
    group timeline by timeline.LifecycleEventId into grouping
    let lifecyleEvent = lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First()
    select new CompletionTimeViewModel()
    {
        Name = lifecyleEvent.LifecycleEventName,
        DisplayName = lifecyleEvent.LifecycleEventDisplayName
    };

Upvotes: 2

Femaref
Femaref

Reputation: 61497

var completionTimeModels =
    from timeline in processTimelines 
    group timeline by timeline.LifecycleEventId into grouping
    let current = lifecycleEvents.Where(i => i.LifecycleEventId == grouping.Key).First()
    select new CompletionTimeViewModel()
    {
            // How to avoid repeating the same query to find the life cycle event?
        Name = current.LifecycleEventName,
        DisplayName = current.LifecycleEventDisplayName
    };

Upvotes: 1

Related Questions