Extension methods for converting IQueryable<T> and IEnumerable<T> to ReadOnlyCollection<T>

和自甴很熟 提交于 2019-12-11 04:29:25

问题


How to write extension methods for converting IQueryable<T> and IEnumerable<T> to ReadOnlyCollection<T>?

Thanks


回答1:


public static ReadOnlyCollection<T> AsReadOnlyCollection<T>(this IEnumerable<T> source)
{
    if(source == null)
      throw new ArgumentNulLException("source");

    IList<T> list = source as IList<T> ?? source.ToList();
    return new ReadOnlyCollection<T>(list);
}

Note that there is no such thing as "converting" an IEnumerable<T> in this case (as with all other methods in the LINQ stack), you will get back a different object than before.




回答2:


List<T> already contains an extension method AsReadOnly(), so just do something like:

queryable.ToList().AsReadOnly()


来源:https://stackoverflow.com/questions/5522654/extension-methods-for-converting-iqueryablet-and-ienumerablet-to-readonlycol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!