Prompt Detail:
how can i make this method more efficient
public async Task<TaskPatternDto[]> Handle(GetTaskPatternQuery query, CancellationToken cancellationToken)
{
var filteredPatterns = new List<List<TaskPatternDto>>();
query.MachineIds = query.MachineIds.Distinct().ToArray();
_validator.ValidateAndThrow(query);
try
{
var entities = _context.Pattern
.WhereIf(query.PatternId.HasValue, x => x.PatternId == query.PatternId)
.WhereIf(query.IstStatic.HasValue, x => x.isStatic == query.IstStatic);
var dto = (await Task.FromResult(_mapper.Map<TaskPatternDto[]>(entities))).ToList();
query.MachineIds.ToList().ForEach( x =>
{
var filtered = dto.Where(p => p.MachineId == x).ToList();
filteredPatterns.Add(filtered);
});
var flatterned = filteredPatterns.SelectMany(i => i);
flatterned.ToList().ForEach(x =>
{
if (_context.ScheduledTask.Where(e => e.PatternId == x.PatternId).Any())
x.PatternType = 1;
else
x.PatternType = 2;
});
return flatterned.ToArray();
}
catch (Exception ex)
{
throw new Exception(GetType().Name, ex);
}
}
Add a comment