使用 LINQ 和 Subselect 投影将 Type1 转换为 type2
在下面的代码中,我想要 TList 的项目 ID 和名称,并将它们转换为 List。我该怎么做?
List<ListItem> nameItems = new List<ListItem>();
TList<ProductCode> items = GetAllProductCode();
//WANT TO SUBSELECT ID, NAME OF ITEMS IN nameItems
nameItems = (from item in items select new (item.Id, item.Name)).Cast<ListItem>();
In the following code I want the project Id and name of TList and cast them to List. How do I do that?
List<ListItem> nameItems = new List<ListItem>();
TList<ProductCode> items = GetAllProductCode();
//WANT TO SUBSELECT ID, NAME OF ITEMS IN nameItems
nameItems = (from item in items select new (item.Id, item.Name)).Cast<ListItem>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使您将其更改为
new { item.Id, item.Name }
,转换也会失败,因为您实际上并没有选择ListItem< /代码>值。
您需要编写一个创建
ListItem
实例的投影。目前尚不清楚这是一个内置的ListItem
类还是您自己的类,但类似这样的东西很可能正是您想要的:如果您能告诉我们更多有关
ListItem
的信息> 是的,这会有很大帮助。(也不清楚为什么你在标题中提到子选择投影 - 我在问题中看不到与子选择相关的任何内容。)
Well even after you've changed that to
new { item.Id, item.Name }
the cast will fail, because you're not actually selectingListItem
values.You need to write a projection which creates instances of
ListItem
. It's not clear whether this is a built-inListItem
class or your own one, but something like this may well be what you want:If you could tell us more about what
ListItem
is, that would help a lot.(It's also not clear why you're mentioning subselect projections in the title - I can't see anything relevant to subselects within the question.)