转换为List <T>以返回功能

Max*_*imc 1 c# inheritance function list

所以我试图创建一个返回数据列表的函数,数据有很多"子"类,其中一个是注释但是,如果日期的类型是注释(我用IF语句测试)那么我想orderby编辑日期而不是id(ID在所有数据对象上都可用,而编辑日期仅在评论类中可用).所以,而不是做TypeOf我做TypeOf然后我能够在编辑日期订购它然而,它想要返回一个List然后我需要它作为一个List,但是我已经google了一个小时+没有运气找到关于如何转换它.这是方法:

private List<T> GetAllData<T>() where T : Data, new()
    {
        List<T> TmpList = new List<T>();
        if (typeof(T) == typeof(Comment))
        {
            TmpList = _newdb.Data.OfType<Comment>().OrderBy(x => x.EditDate).ToList();
            // THIS ABOVE doesn t work ofc since it wants to return a List<Comment> but TmpList is a List<T>

            //List<Comment> TmpComments = _newdb.Data.OfType<Comment>().OrderBy(x => x.EditDate).ToList();
            // List<T> tempzor = new List<T>(TmpComments.ToList());
            //TmpList = (List<T>(TmpComments));
            // TmpList = TmpComments.ConvertAll;
        }
        else
        {
            TmpList = _newdb.Data.OfType<T>().OrderBy(x => (x.Id)).ToList();
        }
        return TmpList;
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Mat*_*ten 5

您可以投射整个列表:

TmpList = _newdb.Data.OfType<Comment>().OrderBy(x => x.EditDate).Cast<T>().ToList();
Run Code Online (Sandbox Code Playgroud)