无法隐式转换类型&#39; System.Collections.Generic.List <anonymoustype#1>&#39;到&#39; System.Collections.Generic.List&lt;&gt;&#39; </anonymoustype#1>

时间:2014-11-28 06:26:08

标签: c# generics

我已经看到了stackoverflow中提供的所有解决方案,但没有得到解决方案。以下是我的代码。

private static List<CombinedData> CombineReport(List<TimesheetUserPaycodeReport> timesheetUserPayCodeData, List<TimesheetReportData> reportData)
        {
            List<CombinedData> combinedReportData = new List<CombinedData>();
            return combinedReportData = (from ts in timesheetUserPayCodeData
            join rd in  reportData on new {ts.LoginName,ts.EntryDateString } equals new {rd.LoginName,rd.EntryDateString }
            select new { rd.EmployeeId,rd.LoginName, rd.LastName, rd.FirstName,rd.StartDateString,
                rd.EndDateString,rd.UserId,rd.EntryDateString,rd.ApprovalStatus,ts.PayCodeHours,
                ts.PayCodeCode,rd.ProjectCode,rd.OTRTicket,rd.ActivityCode,rd.ExportOn,rd.ApprovedOnString,rd.SubmittedOnString,rd.TimesheetId}).ToList();   

我收到以下错误:

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<TimeSheetExport.CombinedData>

2 个答案:

答案 0 :(得分:3)

  

您尝试从某个方法返回匿名类型列表   需要返回List。 新{} 会创建    AnonymousType 列表,因此您需要将列表创建为   返回你的方法的类型。

我猜,您的CombinedData类包含您要返回的所有字段,然后只需更改您的查询,如下所示:

private static List<CombinedData> CombineReport(List<TimesheetUserPaycodeReport> timesheetUserPayCodeData, List<TimesheetReportData> reportData)
        {
            List<CombinedData> combinedReportData = new List<CombinedData>();
            return combinedReportData = (from ts in timesheetUserPayCodeData
            join rd in  reportData on new {ts.LoginName,ts.EntryDateString } equals new {rd.LoginName,rd.EntryDateString }
            select new CombinedData   /// Create CombinedData object here, not anonymous type
            {  
              EmployeeId = rd.EmployeeId,
              LoginName = rd.LoginName, 
              LastName = rd.LastName, 
             ------ so on for remaining fields
             }).ToList();

答案 1 :(得分:0)

您尝试创建匿名类型列表而不是列表。 尝试

... select new CombinedData(rd.EmployeeId,rd.LoginName, rd.LastName, rd.FirstName,rd.StartDateString,
            rd.EndDateString,rd.UserId,rd.EntryDateString,rd.ApprovalStatus,ts.PayCodeHours,
            ts.PayCodeCode,rd.ProjectCode,rd.OTRTicket,rd.ActivityCode,rd.ExportOn,rd.ApprovedOnString,rd.SubmittedOnString,rd.TimesheetId);
相关问题