forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionExtensions.cs
More file actions
50 lines (44 loc) · 1.55 KB
/
CollectionExtensions.cs
File metadata and controls
50 lines (44 loc) · 1.55 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
using System;
using System.Collections.Generic;
namespace ServiceStack
{
public static class CollectionExtensions
{
public static ICollection<T> CreateAndPopulate<T>(Type ofCollectionType, T[] withItems)
{
if (withItems == null)
return null;
if (ofCollectionType == null)
return new List<T>(withItems);
var genericType = ofCollectionType.FirstGenericType();
var genericTypeDefinition = genericType != null
? genericType.GetGenericTypeDefinition()
: null;
#if !XBOX
if (genericTypeDefinition == typeof(HashSet<>))
return new HashSet<T>(withItems);
#endif
if (genericTypeDefinition == typeof(LinkedList<>))
return new LinkedList<T>(withItems);
var collection = (ICollection<T>)ofCollectionType.CreateInstance();
foreach (var item in withItems)
{
collection.Add(item);
}
return collection;
}
public static T[] ToArray<T>(this ICollection<T> collection)
{
var to = new T[collection.Count];
collection.CopyTo(to, 0);
return to;
}
public static object Convert<T>(object objCollection, Type toCollectionType)
{
var collection = (ICollection<T>) objCollection;
var to = new T[collection.Count];
collection.CopyTo(to, 0);
return CreateAndPopulate(toCollectionType, to);
}
}
}