mar*_*ith 0 c# linq ienumerable asp.net-mvc-4
我有一个方法从缓存中返回一个对象,我用它来填充系统中的选择列表.
var r = CacheHelper.GetCacheItem(...);
return new SelectList((IEnumerable)r, "Id", "Name");
Run Code Online (Sandbox Code Playgroud)
r 是类型的 System.Collections.Generic.List<<>f__AnonymousType39<string,int,string>>
通过使用IEnumerable enumerable = (IEnumerable)r;我看到
enumerable如下所示:
[0]: { Name = "Lost", Id = 1, Area = null }
[1]: { Name = "Found", Id = 2, Area = null }
[2]: { Name = "Stock Adjustment", Id = 3, Area = null }
...
Run Code Online (Sandbox Code Playgroud)
我希望能够使用LINQ来查询结果集以返回子集,同时将完整列表保留在内存中.就像是:
var s = enumerable.Where(x => x.Area == "myarea");
Run Code Online (Sandbox Code Playgroud)
类似的SO问题的答案建议使用ToList(),但我不能在enumerable没有收到System.Collections.IEnumerable' does not contain a definition for 'ToList'..错误消息的情况下调用任何LINQ方法.(我在代码中的其他位置使用ToList(),因此我有一个有效的引用System.Linq.
理想情况下,您应该在整个系统中保留类型信息 - 并可能创建具有相关属性的命名类型.然后你可以回到IEnumerable<SomeConcreteType>以后.
如果您不能这样做,并假设您使用的是C#4和.NET 4或更高版本,则可以使用动态类型:
IEnumerable<dynamic> enumerable = (IEnumerable<dynamic>) r;
...
var s = enumerable.Where(x => x.Area == "myarea");
Run Code Online (Sandbox Code Playgroud)