What is the difference between ((IEnumerable)source).OfType<T>()
and source as IEnumerable<T>
For me they look similar, but they are not!
source
is of type IEnumerable<T>
, but it is boxed as an object
.
Edit
Here is some Code:
public class PagedList<T> : List<T>, IPagedList
{
public PagedList(object source, int index, int pageSize, int totalCount)
{
if (source == null)
throw new ArgumentNullException("The source is null!");
// as IEnumerable<T> gives me only null
IEnumerable<T> list = ((IEnumerable)source).OfType<T>();
if (list == null)
throw new ArgumentException(String.Format("The source is not of type {0}, the type is {1}", typeof(T).Name, source.GetType().Name));
PagerInfo = new PagerInfo
{
TotalCount = totalCount,
PageSize = pageSize,
PageIndex = index,
TotalPages = totalCount / pageSize
};
if (PagerInfo.TotalCount % pageSize > 0)
PagerInfo.TotalPages++;
AddRange(list);
}
public PagerInfo PagerInfo { get; set; }
}
On another place I create an instance of PagedList
public static object MapToPagedList<TSource, TDestination>(TSource model, int page, int pageSize, int totalCount) where TSource : IEnumerable
{
var viewModelDestinationType = typeof(TDestination);
var viewModelDestinationGenericType = viewModelDestinationType.GetGenericArguments().FirstOrDefault();
var mappedList = MapAndCreateSubList(model, viewModelDestinationGenericType);
Type listT = typeof(PagedList<>).MakeGenericType(new[] { viewModelDestinationGenericType });
object list = Activator.CreateInstance(listT, new[] { (object) mappedList, page, pageSize, totalCount });
return list;
}
If anyone can tell me why I have to cast the mappedList to object, I would be really thankful :)
And here the MapAndCreateSubList method and the Map delegate:
private static List<object> MapAndCreateSubList(IEnumerable model, Type destinationType)
{
return (from object obj in model select Map(obj, obj.GetType(), destinationType)).ToList();
}
public static Func<object, Type, Type, object> Map = (a, b, c) =>
{
throw new InvalidOperationException(
"The Mapping function must be set on the AutoMapperResult class");
};