What is the proper way to create a variable that will house a list of anonymous objects that are generated through a LINQ query
while keeping the variable declaration outside of a try/catch
and the assignment being handled inside of a try/catch
?
At the moment I'm declaring the variable as IEnumerable<object>
, but this causes some issues down the road when I'm trying to use it later...
i.e.
var variableDeclaration;
try
{
// ...
assignment
// ...
}
catch...
EDIT:
If it's relevant (don't think it is) the list of objects is being returned as a Json
result from an MVC3 action. I'm trying to reduce the time that some using
statements are open with the DB as I'm having some performance issues that I'm trying to clear up a bit. In doing some of my testing I came across this issue and can't seem to find info on it.
EDIT 2:
If I could request the avoidance of focusing on LINQ
. While LINQ is used the question is more specific to the scoping issues associated with Anonymous
objects. Not the fact that LINQ is used (in this case) to generate them.
Also, a couple of answers have mentioned the use of dynamic
while this will compile it doesn't allow for the usages that I'm needing later on the method. If what I'm wanting to do isn't possible then at the moment the answer appears to be to create a new class
with the definition that I'm needing and to use that.
It's possible to get around this by creating a generic Cast
method as outlined by Jon Skeet here. It will work and give you the intellisense you want. But, at this point, what's wrong with creating a custom type for your linq method?
public class MyClass
{
public int MyInt { get; set; }
}
IEnumerable<MyClass> myClass =
//Some Linq query that returns a collection of MyClass