简体   繁体   English

转换为清单 <T> 用于功能返回

[英]Convert to List<T> for return of function

So I am trying to make a Function which returns a list of data, data has many "child" classes and one of them is Comment however, if the type of date is Comment (Which I test with the IF statement) then I want to orderby Edit date and NOT by id (ID is available on all data objects, while edit date is only available on the comments class). 因此,我尝试制作一个返回数据列表的函数,数据具有许多“子”类,其中一个是“注释”,但是,如果日期类型是“注释”(我使用IF语句进行测试),那么我想orderby编辑日期,而不按id(ID在所有数据对象上均可用,而编辑日期仅在comment类上可用)。 So instead of doing TypeOf I do TypeOf and thenI am able to order it on the edit date however, it want to return a List then but I need it to be a List, However I have been googleing for an hour + and no luck finding on how to convert it. 因此,除了执行TypeOf之外,我也可以在编辑日期订购它,但是它想返回一个List,但是我需要将它作为List,但是我一直在Google搜索一个小时+并且没有运气关于如何转换它。 Here is the method: 方法如下:

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

Thanks in advance! 提前致谢!

您可以投射整个列表:

TmpList = _newdb.Data.OfType<Comment>().OrderBy(x => x.EditDate).Cast<T>().ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM