-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathArrayExtensions.cs
70 lines (54 loc) · 1.39 KB
/
ArrayExtensions.cs
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
// LinqPad 6
void Main()
{
int[] arr = { 1, 2, 3, 4, 2};
/*
var sameArr = arr.Fill(9,3);
sameArr.Dump(); // 1, 2, 3, 9, 9
arr.Dump(); // 1, 2, 3, 9, 9
*/
/*
var copyArr = arr.FillAndCopy(9,3);
copyArr.Dump(); // 1, 2, 3, 9, 9
arr.Dump(); // 1, 2, 3, 4, 2
*/
/*
var sameMappedArr = arr.Map(a => (int)Math.Pow(a,3),2);
sameMappedArr.Dump(); // 1, 2, 27, 64, 8
arr.Dump(); // 1, 2, 27, 64, 8
*/
/*
var copyMappedArr = arr.MapAndCopy(a => (int)Math.Pow(a, 3), 2);
copyMappedArr.Dump(); // 1, 2, 27, 64, 8
arr.Dump(); // 1, 2, 3, 4, 2
*/
}
public static class ArrayExtensions
{
public static int[] FillAndCopy(this int[] array,int value,int startIndex = 0)
{
var tempArray = array.ToArray();
foreach (ref int item in tempArray.AsSpan(startIndex))
item = value;
return tempArray;
}
public static int[] Fill(this int[] array, int value, int startIndex = 0)
{
foreach (ref int item in array.AsSpan(startIndex))
item = value;
return array;
}
public static int[] Map(this int[] array, Func<int,int> func, int startIndex = 0)
{
foreach (ref int item in array.AsSpan(startIndex))
item = func(item);
return array;
}
public static int[] MapAndCopy(this int[] array, Func<int, int> func, int startIndex = 0)
{
var tempArray = array.ToArray();
foreach (ref int item in tempArray.AsSpan(startIndex))
item = func(item);
return tempArray;
}
}