How can I declare a variable outside the block when the variable defines an anonymous class in C #

I have the following code and it works well:

var _data = (from qu in _que.GetAll( u => u.company == "GE" ) select new { qu.name, qu.address }); 

Signature of the GetALL Method

 ICollection<T> GetAll(Expression<Func<T, bool>> predicate); 

Now I need to enclose the above in some block so that it becomes:

 { var _data = (from qu in _que.GetAll( u => u.company == "GE" ) select new { qu.name, qu.address }); } var _abc = _data; <<< doesn't work now 

Once I do this, _data becomes local, and I cannot access it from outside the block. I assume that I need to make the _data declaration outside the block. But what I declare is this too, as they print the return and put in _data, is an anonymous type. Is there a way that I can declare _data without having to modify the query or make up some type of return value?

+4
source share
3 answers

Your question is incomprehensible, but I think I understand it. Personally, I try to avoid this, but you can do something like:

 // I'm assuming name and address are strings var _data = Enumerable.Repeat(new { name = "", address = "" }, 0); _data = null; // Never actually want to use that value if (someCondition) { _data = from qu in _que.GetAll(u => u.company == "GE") select new { qu.name, qu.address }; } 

As long as you use the same property names and types, two anonymous types here will be equivalent, so you can complete the second task without any problems. Please note that I changed the formatting of the query expression - I think it looks a lot clearer, because earlier it looked like the GetAll argument was part of the query expression itself.

Given that the expression of your request is just one choice, I would probably just write:

 _data = _que.GetAll(u => u.company == "GE") .Select(qu => new { qu.name, qu.address }); 
+5
source

At least with Resharper, and if you don't mind losing var , you can quickly change it to an explicit type declaration, and then transfer it to the outer scope. Just a few clicks. But agree with Mark and John, I too often come across this, and this is often messy.

0
source

It depends on the surrounding code, but you can delay Select until there is a block.

 ICollection<SomeType> _data = null; ... { _data = _que.GetAll(u => u.company == "GE"); } ... var _abc = from qu in _data select new { qu.name, qu.address }; 
0
source

All Articles