3

我调用了一个GetData返回IQueryable对象的调用。我使用以下 LINQSelectMany过滤并选择了我需要返回的字段,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 错误?谢谢。

4

3 回答 3

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 }
于 2012-12-03T16:44:13.003 回答
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具有默认的无参数构造函数。

于 2012-12-03T16:49:30.247 回答
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();

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

于 2012-12-03T16:43:27.687 回答