我调用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错误?感谢。
答案 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
有一个默认的无参数构造函数。