Fixing Scope Issue With Variable Of Type Var
In the code below, I need to set "Variable1" to an arbitrary value so I don't get into scope issues further below. What is the best arbitrary value for a variable of type var, or is there a better way to avoid the scope issue I'm having?
var Variable1;
if(Something == 0)
{
//DB = DatabaseObject
Variable1 =
from a in DB.Table
select new {Data = a};
}
int RowTotal = Var开发者_运维问答iable1.Count();
Well, you could do:
// It's not clear from your example what the type of Data should
// be; adjust accordingly.
var variable1 = Enumerable.Repeat(new { Data = 0 }, 0).AsQueryable();
if (something == 0)
{
//DB = DatabaseObject
variable1 = from a in DB.Table
select new {Data = a};
}
int rowTotal = variable1.Count();
This is effectively "typing by example". To be honest, I'd try to avoid it - but it's hard to know exactly how I'd do so without seeing the rest of the method. If possible, I'd try to keep the anonymous type scope as tight as possible.
Note: in this case you could just select a
instead of an anonymous type. I'm assuming your real use case is more complex. Likewise if you genuinely only need the row total, then set that inside the braces. The above solution is only applicable if you really, really need the value of the variable later on.
Are you using Variable1 later in your code, or just to find the row count.
If the latter, it's just:
int RowTotal = DB.Table.Count();
If for the full block:
int RowTotal = (Something == 0) ? DB.Table.Count() : 0;
It looks like you can define it as IEnumerable. Then you can use the count function like you are trying to.
精彩评论