-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAppend-to-array.linq
71 lines (58 loc) · 1.35 KB
/
Append-to-array.linq
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
<Query Kind="Program" />
void Main()
{
int[] array = { 1, 2, 3, 4 };
int item = 5;
int[] result = array.Append(item);
String.Join(",", result).Dump();
result = array.AppendConcat(item);
String.Join(",", result).Dump();
result = array.AppendCopyTo(item);
String.Join(",", result).Dump();
result = array.AppendToList(item);
String.Join(",", result).Dump();
//For benchmark information on executing these scenarios please see:
//https://github.com/Jaxelr/Benchmarks/tree/master/AppendBenchmark
}
static class Extensions
{
public static T[] Append<T>(this T[] array, T item)
{
if (array == null)
{
return new T[] { item };
}
var result = new T[array.Length + 1];
for (int i = 0; i < array.Length; i++)
{
result[i] = array[i];
}
result[array.Length] = item;
return result;
}
public static T[] AppendCopyTo<T>(this T[] array, T item)
{
if (array == null)
{
return new T[] { item };
}
var result = new T[array.Length + 1];
array.CopyTo(result, 0);
result[array.Length] = item;
return result;
}
public static T[] AppendConcat<T>(this T[] array, T item)
{
if (array == null)
{
return new T[] { item };
}
return array.Concat(new T[] { item }).ToArray();
}
public static T[] AppendToList<T>(this T[] array, T item)
{
var list = new List<T>(array);
list.Add(item);
return list.ToArray();
}
}