-
-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathCollectionConverter.cs
More file actions
166 lines (143 loc) · 5.46 KB
/
CollectionConverter.cs
File metadata and controls
166 lines (143 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
using System.Collections;
using JsonApiDotNetCore.Resources;
namespace JsonApiDotNetCore;
internal sealed class CollectionConverter
{
private static readonly HashSet<Type> HashSetCompatibleCollectionTypes =
[
typeof(HashSet<>),
typeof(ISet<>),
typeof(IReadOnlySet<>),
typeof(ICollection<>),
typeof(IReadOnlyCollection<>),
typeof(IEnumerable<>)
];
public static CollectionConverter Instance { get; } = new();
private CollectionConverter()
{
}
/// <summary>
/// Creates a collection instance based on the specified collection type and copies the specified elements into it.
/// </summary>
/// <param name="source">
/// Source to copy from.
/// </param>
/// <param name="collectionType">
/// Target collection type, for example: <code><![CDATA[
/// typeof(List<Article>)
/// ]]></code> or <code><![CDATA[
/// typeof(ISet<Person>)
/// ]]></code>.
/// </param>
public IEnumerable CopyToTypedCollection(IEnumerable source, Type collectionType)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(collectionType);
Type concreteCollectionType = ToConcreteCollectionType(collectionType);
dynamic concreteCollectionInstance = Activator.CreateInstance(concreteCollectionType)!;
foreach (object item in source)
{
concreteCollectionInstance.Add((dynamic)item);
}
return concreteCollectionInstance;
}
/// <summary>
/// Returns a compatible collection type that can be instantiated, for example: <code><![CDATA[
/// IList<Article> -> List<Article>
/// ]]></code> or
/// <code><![CDATA[
/// ISet<Article> -> HashSet<Article>
/// ]]></code>.
/// </summary>
private Type ToConcreteCollectionType(Type collectionType)
{
ArgumentNullException.ThrowIfNull(collectionType);
if (collectionType is { IsInterface: true, IsGenericType: true })
{
Type openCollectionType = collectionType.GetGenericTypeDefinition();
if (HashSetCompatibleCollectionTypes.Contains(openCollectionType))
{
return typeof(HashSet<>).MakeGenericType(collectionType.GenericTypeArguments[0]);
}
if (openCollectionType == typeof(IList<>) || openCollectionType == typeof(IReadOnlyList<>))
{
return typeof(List<>).MakeGenericType(collectionType.GenericTypeArguments[0]);
}
}
return collectionType;
}
/// <summary>
/// Returns a collection that contains zero, one or multiple resources, depending on the specified value.
/// </summary>
public IReadOnlyCollection<IIdentifiable> ExtractResources(object? value)
{
return value switch
{
List<IIdentifiable> resourceList => resourceList.AsReadOnly(),
HashSet<IIdentifiable> resourceSet => resourceSet.AsReadOnly(),
IReadOnlyCollection<IIdentifiable> resourceCollection => resourceCollection,
IEnumerable<IIdentifiable> resources => resources.ToArray().AsReadOnly(),
IIdentifiable resource => [resource],
_ => Array.Empty<IIdentifiable>()
};
}
/// <summary>
/// Returns the number of elements in a collection of resources.
/// </summary>
public int GetCount(IEnumerable source)
{
ArgumentNullException.ThrowIfNull(source);
return source switch
{
List<IIdentifiable> resourceList => resourceList.Count,
HashSet<IIdentifiable> resourceSet => resourceSet.Count,
IReadOnlyCollection<IIdentifiable> resourceCollection => resourceCollection.Count,
IEnumerable<IIdentifiable> resources => resources.Count(),
_ => source.Cast<object>().Count()
};
}
/// <summary>
/// Returns the element type if the specified type is a generic collection, for example: <code><![CDATA[
/// IList<string> -> string
/// ]]></code> or
/// <code><![CDATA[
/// IList -> null
/// ]]></code>.
/// </summary>
public Type? FindCollectionElementType(Type? type)
{
if (type != null)
{
Type? enumerableClosedType = IsEnumerableClosedType(type) ? type : null;
enumerableClosedType ??= type.GetInterfaces().FirstOrDefault(IsEnumerableClosedType);
if (enumerableClosedType != null)
{
return enumerableClosedType.GenericTypeArguments[0];
}
}
return null;
}
private static bool IsEnumerableClosedType(Type type)
{
bool isClosedType = type is { IsGenericType: true, ContainsGenericParameters: false };
return isClosedType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
/// <summary>
/// Indicates whether a <see cref="HashSet{T}" /> instance can be assigned to the specified type, for example:
/// <code><![CDATA[
/// IList<Article> -> false
/// ]]></code> or <code><![CDATA[
/// ISet<Article> -> true
/// ]]></code>.
/// </summary>
public bool TypeCanContainHashSet(Type collectionType)
{
ArgumentNullException.ThrowIfNull(collectionType);
if (collectionType.IsGenericType)
{
Type openCollectionType = collectionType.GetGenericTypeDefinition();
return HashSetCompatibleCollectionTypes.Contains(openCollectionType);
}
return false;
}
}