2016-11-14 25 views
0

我試圖對另一個List<>內的List<>內的每個項目執行運行擴展方法以返回給定類型(由擴展方法返回)的集合。另一個列表中的列表中的項目的擴展方法

我最初嘗試(和失敗)做到這一點使用LINQ,但我有以下幾點:

 var dataset = GetReportDataset(org); 

     var reportData = new List<InterventionAndNeetRiskReportLineModel>(); 

     foreach (var record in dataset) 
     { 
      foreach (var inter in record.InterventionHistory) 
      { 
       reportData.Add(inter.ToInterventionAndNeetRiskReportLineModel()); 
      } 
     } 
     return _reportWriter.ReportCsvStream(reportData); 

所以我的問題是,我怎麼能突出我的擴展方法的結果,在每個項目使用linq的孩子集合?

UPDATEToInterventionAndNeetRiskReportLineModel()擴展方法

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 
     }; 
    } 
+0

目前還不清楚擴展方法是什麼,也不清楚「失敗」的含義。請提供[mcve]。 –

+2

你只是想找到屬於另一個列表的一部分列表中的所有元素?你不需要擴展。 – Brandon

+0

添加擴展方法 – JimmyB

回答

4

我不能完全確定要分成一個擴展方法,它的代碼有問題的一部分。就寫作而言,不要專注於擴展方法部分,它與其他函數沒什麼區別。

您可以使用SelectMany爲了得到InterventionHistory對象和Select的平面列表,以轉換爲InterventionAndNeetRiskReportLineModelToList的最終結果爲列表,而不是IEnumerable<T>如果你真的很需要那。

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

所以,也許你想要一個像

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

擴展方法和使用它作爲

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

...正如我所說的,它並不完全清楚,其中一部分你想重構爲擴展方法。

+1

SelectMany是我之後的解決方案。謝謝!!我的問題可能更清楚,但感謝您的努力。 – JimmyB

相關問題