JimmyB JimmyB - 1 year ago 64
C# Question

Extension method on Item in List within another List

I'm trying to perform an run an extension method on every item within a

that is inside another
to return collection of a given type (returned by the extension method).

I initially tried (and failed) to do this using linq, but I have the following:

var dataset = GetReportDataset(org);

var reportData = new List<InterventionAndNeetRiskReportLineModel>();

foreach (var record in dataset)
foreach (var inter in record.InterventionHistory)
return _reportWriter.ReportCsvStream(reportData);

So my question is, how can I project the result of my extension method for each item in the child collection using linq?

extension method

public static InterventionAndNeetRiskReportLineModel ToInterventionAndNeetRiskReportLineModel(this InterventionHistory intervention)
return new InterventionAndNeetRiskReportLineModel()
Beneficiary = intervention.Person.Beneficiary,
CourseTitle = intervention.CourseTitle,
CaseNotes = intervention.CaseNotes,
EndDate = intervention.EndDate?.ToString(),
StartDate = intervention.StartDate.ToString(),
ParticipantId = intervention.Person.ParticipantId,
FirstEit = intervention.Person.EitScores.GetFirstEitReading().ToString(),
LastEit = intervention.Person.EitScores.GetLastEitReading().ToString(),
FirstLpt = intervention.Person.LptScores.GetFirstLptReading().ToString(),
LastLpt = intervention.Person.LptScores.GetLastLptReading().ToString(),
Gender = intervention.Person.Equalitites.Gender,
HoursAttended = intervention.NoOfHours.ToString(),
LanguageOfDelivery = intervention.DeliveryLanguage,
Providername = intervention.ProviderName,
QanCode = intervention.QanCode,
SchoolCollegeName = intervention.ProviderName

Answer Source

I'm not completely sure which part of the question code you want to separate into an extension method. Also, don't be to focused on the extension method part, its nothing different from other functions, as far as the writing is concerned.

You can use SelectMany in order to get a flat list of InterventionHistory objects and Select in order to convert to InterventionAndNeetRiskReportLineModel and ToList for the final result as list instead of IEnumerable<T> if you really need that.

var reportData = GetReportDataset(org)
    .SelectMany(r => r.InterventionHistory)
    .Select(i => i.ToInterventionAndNeetRiskReportLineModel())

So, maybe you want an extension method like

public static IEnumerable<InterventionAndNeetRiskReportLineModel> ToInterventionRiskReports(this IEnumerable<ReportDataset> _self)
     return _self
        .SelectMany(r => r.InterventionHistory)
        .Select(i => i.ToInterventionAndNeetRiskReportLineModel());

And use it as

var reportData = GetReportDataset(org).ToInterventionRiskReports().ToList();

... as I said, its not completely clear, which part you want to refactor into an extension method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download