33using System . Collections ;
44using System . Collections . Generic ;
55using System . Linq ;
6+ using System . Reflection ;
67using JsonApiDotNetCore . Models ;
78
89namespace JsonApiDotNetCore . Extensions
@@ -13,10 +14,10 @@ internal static class TypeExtensions
1314 /// Extension to use the LINQ cast method in a non-generic way:
1415 /// <code>
1516 /// Type targetType = typeof(TResource)
16- /// ((IList)myList).Cast (targetType).
17+ /// ((IList)myList).CopyToList (targetType).
1718 /// </code>
1819 /// </summary>
19- public static IEnumerable Cast ( this IEnumerable source , Type type )
20+ public static IEnumerable CopyToList ( this IEnumerable source , Type type )
2021 {
2122 if ( source == null ) throw new ArgumentNullException ( nameof ( source ) ) ;
2223 if ( type == null ) throw new ArgumentNullException ( nameof ( type ) ) ;
@@ -29,6 +30,28 @@ public static IEnumerable Cast(this IEnumerable source, Type type)
2930 return list ;
3031 }
3132
33+ /// <summary>
34+ /// Creates a collection instance based on the specified collection type and copies the specified elements into it.
35+ /// </summary>
36+ /// <param name="source">Source to copy from.</param>
37+ /// <param name="collectionType">Target collection type, for example: typeof(List{Article}) or typeof(ISet{Person}).</param>
38+ /// <returns></returns>
39+ public static IEnumerable CopyToTypedCollection ( this IEnumerable source , Type collectionType )
40+ {
41+ if ( source == null ) throw new ArgumentNullException ( nameof ( source ) ) ;
42+ if ( collectionType == null ) throw new ArgumentNullException ( nameof ( collectionType ) ) ;
43+
44+ var concreteCollectionType = collectionType . ToConcreteCollectionType ( ) ;
45+ dynamic concreteCollectionInstance = concreteCollectionType . New < dynamic > ( ) ;
46+
47+ foreach ( var item in source )
48+ {
49+ concreteCollectionInstance . Add ( ( dynamic ) item ) ;
50+ }
51+
52+ return concreteCollectionInstance ;
53+ }
54+
3255 /// <summary>
3356 /// Creates a List{TInterface} where TInterface is the generic for type specified by t
3457 /// </summary>
@@ -99,5 +122,10 @@ public static bool Inherits<T>(this Type concreteType)
99122 /// </summary>
100123 public static bool Inherits ( this Type concreteType , Type interfaceType )
101124 => interfaceType ? . IsAssignableFrom ( concreteType ) == true ;
125+
126+ public static bool ImplementsInterface ( this Type source , Type interfaceType )
127+ {
128+ return source . GetInterfaces ( ) . Any ( type => type == interfaceType ) ;
129+ }
102130 }
103131}
0 commit comments