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

时间:2016-09-01 16:03:46

标签: c# linq

我需要优化我的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子句中创建List<List<StepDTO>>实例而不是选择整个StepDTO来从查询l.H_Scenario.Steps获取。

2 个答案:

答案 0 :(得分:2)

您只需使用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();

答案 1 :(得分:1)

 select (l.H_Scenario.Steps.Where(x => x.IsActivInGlobalApdexCounting == true)).Select(step => new StepDto { // assign values here}).ToList()