【问题标题】:Convert to List<T> for return of function转换为 List<T> 以返回函数
【发布时间】:2012-07-22 00:12:48
【问题描述】:

所以我正在尝试创建一个返回数据列表的函数,数据有许多“子”类,其中一个是 Comment,但是,如果日期类型是 Comment(我用 IF 语句测试),那么我想按编辑日期排序,而不是按 id 排序(ID 可用于所有数据对象,而编辑日期仅可用于 cmets 类)。因此,我没有做 TypeOf,而是做 TypeOf,然后我可以在编辑日期订购它,但是它想返回一个列表,但我需要它是一个列表,但是我已经用谷歌搜索了一个小时 + 并没有找到运气关于如何转换它。方法如下:

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

提前致谢!

【问题讨论】:

  • 看来你需要在某个地方打电话给.Cast&lt;Comment&gt;()
  • 当您调用GetAllData&lt;Comment&gt;() 时,返回List&lt;T&gt; 将是List&lt;Comment&gt;

标签: c# list function inheritance


【解决方案1】:

您可以投射整个列表:

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

【讨论】:

  • 这不起作用:错误 1 ​​无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少演员表?
  • TmpList = _newdb.Data.OfType().OrderBy(x => x.EditDate).Cast().ToList();这确实有效首先需要 Cast 然后 ToList()!谢谢:)
猜你喜欢
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 2019-05-20
相关资源
最近更新 更多