문제

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?

도움이 되었습니까?

해결책

You can use a Ternary operator like:

var result = IsByDescending ? 
               listModelElements.OrderByDescending(x => sort(x)).ToList() :
               listModelElements.OrderBy(x => sort(x)).ToList();

다른 팁

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>.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top