Margarita Spasskaya Margarita Spasskaya - 3 months ago 15
C# Question

Select specific fields from linq query in list

I need to optimise my linq query, it looks like this:

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();


And in order to optimise it I want to select only fields from class step that I need, so I created class
StepDTO
.

Here is class
Step


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


and class
StepDTO


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


The question is how to get from a query
List<List<StepDTO>>
by creating a
StepDTO
instance in select clause instead of selecting whole
l.H_Scenario.Steps
.

Answer

You just need to use Select and create new object instance in it. Here you go:

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();