You can use a Ternary operator like:
var result = IsByDescending ?
listModelElements.OrderByDescending(x => sort(x)).ToList() :
listModelElements.OrderBy(x => sort(x)).ToList();
Vra
I have a method which sorts a list < T > which gets a bool parameter which indicates if to sort by ascending
or by descending
.
I would like to use var
as returned type.
protected void SortlistBy(bool IsByDescending)
{
var result;
// Initialize the var according to parameter value
if (IsByDescending == false)
result = listModelElements.OrderBy(x => sort(x)).ToList();
else
result = listModelElements.OrderByDescending(x => sort(x)).ToList();
}
I get the following error: Implicitly-typed local variables must be initialized
.
Any ideas?
Oplossing
You can use a Ternary operator like:
var result = IsByDescending ?
listModelElements.OrderByDescending(x => sort(x)).ToList() :
listModelElements.OrderBy(x => sort(x)).ToList();
Ander wenke
This is not possible. You have to declare a type.
var
is not a keyword for late-binding.
You simply can't - the type of a variable has to be either explicitly declared or be inferrable at the point of declaration. And, since the variable isn't being assigned anything, its type can't be inferred by the compiler.
Just declare result
as a IEnumerable<T>
or IList<T>
.