使用linq从列表中获取特定的x项

B. *_*Nir 0 c# linq

我试图从我创建的列表中获取特定的x项.

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

我收到以下错误:

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

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

wex*_*man 5

正如KingKing正确指出的那样,你最后错过了".ToList()"调用.没有它,该查询将导致无法转换为List的IQueryable.

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

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

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