if - else初始化var

时间:2014-03-31 11:32:25

标签: c# linq sorting .net-4.0

我有一个方法可以对列表进行排序< T>获取bool参数,指示是按ascending还是按descending排序。

我想使用var作为返回类型。

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();
    }

我收到以下错误:Implicitly-typed local variables must be initialized

尝试初始化为String的null会导致此错误:'string' does not contain a definition for 'ThenBy'

有什么想法吗?

更新:
该方法使派生类能够根据发送的属性对基类中的私有列表进行排序。

 protected void SortlistMBy(Func<MyBaseClass, IComparable> sort, params Func<MyBaseClass, IComparable>[] details )
    {
        var result  =  listOfBase .OrderByDescending(x => sort(x));  

 //HERE WOULD LIKE TO SORT BY DESCENDING  

        foreach(var detail in details)
        {
            result = result.ThenBy(x => detail(x));
        }

        listOfBase = result.ToList();
    }

0 个答案:

没有答案