开发者

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

开发者 https://www.devze.com 2023-02-21 06:20 出处:网络
How to write extensio开发者_Go百科n methods for converting IQueryable<T> and IEnumerable<T> to ReadOnlyCollection<T>?

How to write extensio开发者_Go百科n methods for converting IQueryable<T> and IEnumerable<T> to ReadOnlyCollection<T>?

Thanks


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

queryable.ToList().AsReadOnly()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消