Reputation: 4918
I have a method that returns an object from cache which I use to populate selectlists within the system.
var r = CacheHelper.GetCacheItem(...);
return new SelectList((IEnumerable)r, "Id", "Name");
r
is of type System.Collections.Generic.List<<>f__AnonymousType39<string,int,string>>
By using IEnumerable enumerable = (IEnumerable)r;
I see that
enumerable
looks like this:
[0]: { Name = "Lost", Id = 1, Area = null }
[1]: { Name = "Found", Id = 2, Area = null }
[2]: { Name = "Stock Adjustment", Id = 3, Area = null }
...
I would like to be able to use LINQ toquery the result set to return a subset, while keeping the full list in memory. Something like:
var s = enumerable.Where(x => x.Area == "myarea");
Answers to similar SO questions suggest using ToList(), but I can't call any LINQ methods on enumerable
without getting a System.Collections.IEnumerable' does not contain a definition for 'ToList'..
error message. (I'm using ToList() elsewhere in the code so I have a valid reference to System.Linq
.
Upvotes: 0
Views: 4552
Reputation: 1503449
Ideally, you should keep the type information all the way through the system - and potentially create a named type with the relevant properties. You could then cast back to IEnumerable<SomeConcreteType>
later.
If you can't do that though, and assuming you're using C# 4 and .NET 4 or later, you could use dynamic typing:
IEnumerable<dynamic> enumerable = (IEnumerable<dynamic>) r;
...
var s = enumerable.Where(x => x.Area == "myarea");
Upvotes: 6