How to write extension methods for converting IQueryable<T>
and IEnumerable<T>
to ReadOnlyCollection<T>
?
Thanks
List<T>
已经包含一个扩展方法AsReadOnly()
,因此只需执行以下操作:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.