我需要优化我的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中获取信息。

最佳答案

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

关于c# - 从列表中的linq查询中选择特定字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39276212/

10-09 00:20