How to introduce Let keyword inside Linq statement with Group by

不问归期 提交于 2019-12-23 08:38:04

问题


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

回答1:


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



回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/5596899/how-to-introduce-let-keyword-inside-linq-statement-with-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!