Best type to store a LINQ result in a global variable
I'm writing a report and loading the data to display as soon as the report loads using LINQ.
summaryData = from summary in _entity.Summary
// some constraints here
select new
{
summary.payment_category_desc,
summary.payment_due_amt,
summary.currency_desc
开发者_运维问答 };
I need to consume these results later in a different event(the PrintDetail), in a way that I can , for instance, say:
string name = summaryData[currentIndex].payment_category_desc
Basically what I need is to find how to store the LINQ results in a global variable that I can later enumerate. I've tried IQueriable and it wont let me. I'm also trying to avoid having to create a class with three members in order to be able to use ToList().
Any thoughts?
Edit To be honest, I only just noticed that you were using an anonymous types. As you already know by now, there is no way you can get an anon-type outside your method. However, you can use a C# 4.0 Tuple<>
The following will work when summaryData is passed/defined outside you current method:
summaryData = from summary in _entity.Summary
// some constraints here
select new Tuple<string, DateTime, decimal>
{
summary.payment_category_desc,
summary.payment_due_amt,
summary.currency_desc
};
Whatever it is, if it is a collection/query result, IEnumerable<T>
will work
Be sure to think whether you need to convert to a list (cache the result) with .ToList()
first.
If you don't the original enumerator will get executed multiple times, which could be a (performance) issue. Consider when the enumerator accesses a file that is not longer opened, accessible etc.
Personally I'd avoid using a global variable. You make it harder to test your application when you have a dependency such as a global variable.
I don't know your exact architecture but I'd be tempted to pass the object to the relevant methods that require it. At least this way you can easily mock your object and you reduce the dependency.
Your IQueryable result employs deffered execution. If you are coding that inside of a "using" block, you won't have a connection when you try to access your results (global variable or not).
Try returning a List from your LINQ query via the ToList() extension method.
精彩评论