2013-08-26 54 views
0

我想从我创建的列表中获取特定的x项目。从列表中获取特定的x项目使用linq

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

我得到以下错误:

"Unable to cast object of type 'd__3a`1[AssetManagement.Entities.Item]' to type 'System.Collections.Generic.List`1[AssetManagement.Entities.Item]'."

岂是固定的,为什么会出现这种情况?

回答

5

正如KingKing正确指出的那样,您最后错过了“.ToList()”调用。没有那个,那个查询将导致一个IQueryable不能被转换为List。

作为一个侧节点,我宁愿使用隐式变量类型声明,就像

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

这样一来,就不会抛出例外,甚至没有“ToList”(但也许这止跌” t已经是你的预期了)

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

注意:铸件可以做到只用InheritanceImplementation关系的对象之间。试着记住这一点。

3

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

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

我使用括号兑现查询(from..where..select).ToList();

+0

可以合并'Where'从来不喜欢和'Take'用['TakeWhile'] (http://msdn.microsoft.com/en-us/library/system.linq.enumerable.takewhile.aspx) – Default

+0

@默认我不确定。这些项目可能不在枚举的开始处。 – EZI

+0

ups。误读文档。你是对的 – Default

相关问题