无法将类型'System.Collections.Generic.IEnumerable <anonymoustype#1>'隐式转换为'System.Collections.Generic.List <custom data =“”type =“”> </custom> </anonymoustype#1>

时间:2012-12-03 16:33:18

标签: c# linq

我调用GetData调用,返回IQueryable个对象。我使用以下LINQ SelectMany来过滤并选择我需要的字段 返回List<MyDataType>,我收到以下错误

无法隐式将System.Collections.Generic.List<AnonymousType#1>类型转换为System.Collection.Generic.List<MyDataType>

这是我的代码

List<CASES> caseList = cs.GetData(foiaNumber).ToList();

Dictionary<int, string> NameDict = 
    caseList.ToDictionary(cases => cases.UID, cases =>     cases.NAME);


List<MyDataType> bindingGrdList = 
    caseList.SelectMany(x => x.ListObject)
        .Select(n => 
            new { 
                   SUBMITTER_NAME = NameDict[n.UID], 
                   NUMBER = n.UID, 
                   DATE_SENT = n.DATE_SENT, 
                   DATE_DUE = n.DATE_DUE, 
                   FINAL_DETERMINATION = n.FINAL_DETERMINATION 
                 }).ToList();

如何修复AnonymousType错误?感谢。

3 个答案:

答案 0 :(得分:11)

替换

n => new { SUBMITTER_NAME = NameDict[n.UID], NUMBER = n.UID,
    DATE_SENT = n.DATE_SENT, DATE_DUE = n.DATE_DUE,
    FINAL_DETERMINATION = n.FINAL_DETERMINATION }

n => new MyDataType { SUBMITTER_NAME = NameDict[n.UID], NUMBER = n.UID,
    DATE_SENT = n.DATE_SENT, DATE_DUE = n.DATE_DUE,
    FINAL_DETERMINATION = n.FINAL_DETERMINATION }

答案 1 :(得分:0)

请尝试使用var

var bindingGrdList = caseList.SelectMany(x => x.ListObject).Select(n => new { SUBMITTER_NAME = NameDict[n.UID], NUMBER = n.UID, DATE_SENT = n.DATE_SENT, DATE_DUE = n.DATE_DUE, FINAL_DETERMINATION = n.FINAL_DETERMINATION }).ToList();

这将使它从您的代码中推断出类型,这就是您想要的匿名类型。

答案 2 :(得分:0)

您需要将投射从匿名类型更改为MyDataType。为此,您需要更改Select,如下所示:

List<MyDataType> bindingGrdList = 
    caseList.SelectMany(x => x.ListObject)
        .Select(n => 
            new MyDataType 
                { 
                   SUBMITTER_NAME = NameDict[n.UID], 
                   NUMBER = n.UID, 
                   DATE_SENT = n.DATE_SENT, 
                   DATE_DUE = n.DATE_DUE, 
                   FINAL_DETERMINATION = n.FINAL_DETERMINATION 
                 }).ToList();

注意:我假设这些属性是MyDataType的正确属性,MyDataType有一个默认的无参数构造函数。

相关问题