Declare IEnumerable<T> variable for use later on
Solution 1
The type of the query is IEnumerable<Data>
which you can declare outside the using
block. However, from the comments it is obvious that you cannot enumerate after myObject
has been disposed. If you don't want to pull all elements into a list before leaving the using
block your only option is to do the enumeration inside the using
block. Pulling data from a database requires an open connection to that database etc.
using(myObject.......)
{
var query = csv.Select(x => new Data() { ID = x[27], Raw = String.Join(",", x) });
//Do some stuff
//Now I want to use the result of the query
foreach (var item in query)
...
}
Solution 2
You should take well advantage of IEnumerable
. The beauty of this is your query is not evaluated until you are need. Once you do a ToList()
your query is executed fully. It is well suggested to use IEnumerable
as much as possible.
You just can define IEnumerable<Data>
in the outer scope like this
IEnumerable<Data> myDataList;
using(myObject.......)
{
myDataList =csv.Select(x => new Data() { ID = x[27], Raw = String.Join(",", x) });
}
// do your stuffs
// and just use the IEnumerable<Data> in your foreach loop
foreach(var item in myDataList)
{
// here item is typeof(Data)
}
Solution 3
Declare a variable outside the using block.
Call ToList()
or ToArray()
to execute the query.
List<Data> data=null;
using(myObject.......)
{
data=csv.Select(x => new Data() { ID = x[27], Raw = String.Join(",", x) }).ToList();
}
If it's possible to execute the query after returning from the using
clause you could do:
IEnumerable<Data> data=null;
using(myObject.......)
{
data=csv.Select(x => new Data() { ID = x[27], Raw = String.Join(",", x) });
}
But if that's the case, why are you putting it into the using
clause in the first place?
If the query depends on myObject
not being disposed you have two choices:
- Use
ToList()
to execute the query immediately and load it all into memory. - dispose
myObject
later.
Jon
Updated on June 27, 2022Comments
-
Jon almost 2 years
I have a LINQ query such as:
using(csv.......) { csv.Select(x => new Data() { ID = x[27], Raw = String.Join(",", x) }); } //Do some stuff //Now I want to use the result of the query foreach(var item in ??) { }
The query returns IEnumerable within my
using
statement but how do I declare and then assign a variable so I can use it later on in aforeach
statement?