从linq查询列表中选择特定字段

本文关键字:字段 选择 linq 查询 列表 | 更新日期: 2023-09-27 18:05:25

我需要优化我的linq查询,它看起来像这样:

List<List<Step>> steps = (from LoadTest l in monitoringTask.LoadTests
                     where (l.DateStart > (start - Core.session.timeSpanClientServer)
    && l.DateStart < (stop - Core.session.timeSpanClientServer))
                     orderby l.DateStart ascending
                     select (l.H_Scenario.Steps
                           .Where(x => x.IsActivInGlobalApdexCounting == true))
                           .ToList()).ToList();

为了优化它,我想只从类步骤中选择我需要的字段,所以我创建了类StepDTO

这是Step

 private class Step
        {
            private System.Int64 id;
            private System.Int32 responseTime;
            private H_Scenario h_Scenario;
            /other fields*/
        }

StepDTO

 private class StepDTO
        {
            private System.Int64 id;
            private System.Int32 responseTime;
            private H_Scenario h_Scenario;
        }

问题是如何通过在select子句中创建StepDTO实例而不是选择整个l.H_Scenario.Steps来获得查询List<List<StepDTO>>

从linq查询列表中选择特定字段

您只需要使用Select并在其中创建新的对象实例。给你:

List<List<Step>> steps = (from LoadTest l in monitoringTask.LoadTests
                     where (l.DateStart > (start - Core.session.timeSpanClientServer)
    && l.DateStart < (stop - Core.session.timeSpanClientServer))
                     orderby l.DateStart ascending
                     select (l.H_Scenario.Steps
                               .Where(x => x.IsActivInGlobalApdexCounting == true))
                               //Here is you creating your DTO
                               .Select(x => new StepDTO 
                                     {
                                           id = x.id
                                           responseTime = x.responseTime
                                           h_Scenario = x.h_Scenario
                                     })
                               .ToList()).ToList();
 select (l.H_Scenario.Steps.Where(x => x.IsActivInGlobalApdexCounting == true)).Select(step => new StepDto { // assign values here}).ToList()