0

我正在尝试从我创建的列表中获取特定的 x 项。

List<Item> il = (List<Item>)(from i in AllItems
                             where i.Iid == item.Iid
                             select i).Take(Int32.Parse(item.amount));

我收到以下错误:

“无法将 'd__3a`1[AssetManagement.Entities.Item]' 类型的对象转换为类型 'System.Collections.Generic.List`1[AssetManagement.Entities.Item]'。”

如何修复它,为什么会发生这种情况?

4

3 回答 3

5

正如 KingKing 正确指出的那样,您最后错过了“.ToList()”调用。否则,该查询将导致无法转换为 List 的 IQueryable。

作为一个侧节点,我更喜欢使用隐式变量类型声明,比如

var il = (from i in AllItems
    where i.Iid == item.Iid
    select i).Take(Int32.Parse(item.amount)).ToList();

这样,即使没有“ToList”,它也不会抛出异常(但也许它不会是你所期望的)

于 2013-08-26T21:58:09.033 回答
3

这种语法不是更具可读性吗?(与您的查询的唯一区别是ToList()

List<Item> il = AllItems.Where(i => i.Iid == item.Iid)
                        .Take(Int32.Parse(item.amount))
                        .ToList();

我从不喜欢使用括号来实现查询(from..where..select).ToList();

于 2013-08-26T21:59:23.333 回答
3
List<Item> il = (from i in AllItems
                 where i.Iid == item.Iid
                 select i).Take(Int32.Parse(item.amount)).ToList();

注意:只能在具有InheritanceorImplementation关系的对象之间进行转换。试着记住这一点。

于 2013-08-26T21:54:09.633 回答