Click here to Skip to main content
15,906,081 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi, i want to use var type of declarations as globally, i used like this, but it is not accepting, how can i declare this type of variable globally. or do we have another declarations to store linq query result. simply

var testdata;
int count;//count value is coming through method parameters as 1 or 2 or 3, here i have declared as sample
if(count==1)
{
testdata=(from s in spe.contacts select s).orderbyDesending(x=>x.id).take(1);
}
C#
else if(count==2)
{
testdata=(from s in spe.contacts select s).orderbyDesending(x=>x.id).take(2);
}





C#
if(count==3)
{
testdata=(from s in spe.contacts select s).orderbyDesending(x=>x.id).take(3);
}


but it is not accepting, please help me to solve this.
Posted

In this specific case, you can just use count as argument for Take:
C#
var testdata = (from s in spe.contacts select s).OrderByDesending(x=>x.id).Take(count);

In other cases, if you do not return an anonymous type, you can use IQueryable<Type>, where Type is the type of the elements you return.
C#
IQueryable<Type> testdata = null;
// your if statements here

// after the if statements:
if (testdata != null)
{
    // continue
}
else
{
    // testdata is null, none of the code in the previous if statements has been executed
}
 
Share this answer
 
v2
Comments
pavan_ kumar 25-Sep-14 0:18am    
thanks, i forgot to take directly count as parameter, once again thanks for remind me
Thomas Daniels 25-Sep-14 11:14am    
You're welcome!
There is nothing to "define globally", or anyhow. There is no such thing as "var type".

When you declare a variable using var, it is strictly equivalent to writing on of the concrete fully-defined types. You just assume that the compiler can infer this type from the context of your code and "automatically substitute" this type instead of var, as if you did it with your own hands. If unambiguous inference is not possible, the compiler will give you a syntax error with proper explanation of ambiguity.

Please see:
http://en.wikipedia.org/wiki/Type_inference[^],
http://msdn.microsoft.com/en-us/library/bb384061.aspx[^].

—SA
 
Share this answer
 
v2
Comments
Thomas Daniels 24-Sep-14 14:11pm    
5'ed.
Sergey Alexandrovich Kryukov 24-Sep-14 15:11pm    
Thank you very much.
—SA
pavan_ kumar 25-Sep-14 1:02am    
thanks
Sergey Alexandrovich Kryukov 25-Sep-14 1:59am    
You are welcome. Will you accept this answer formally, too?
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900