-
Notifications
You must be signed in to change notification settings - Fork 636
/
Copy pathList.cs
1971 lines (1764 loc) · 76.9 KB
/
List.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
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using Autodesk.DesignScript.Runtime;
using DSCore.Properties;
#endregion
namespace DSCore
{
#region public methods
/// <summary>
/// Methods for creating and manipulating Lists.
/// </summary>
[IsVisibleInDynamoLibrary(false)]
public static class List
{
/// <summary>
/// Returns an Empty List.
/// </summary>
/// <returns name="list">Empty list.</returns>
/// <search>empty list, emptylist,[]</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Empty
{
get { return new ArrayList(); }
}
/// <summary>
/// Creates a new list containing all unique items in the given list.
/// </summary>
/// <param name="list">List to filter duplicates out of.</param>
/// <returns name="list">Filtered list.</returns>
/// <search>removes,duplicates,remove duplicates,cull duplicates,distinct,listcontains</search>
[IsVisibleInDynamoLibrary(true)]
public static IList UniqueItems(IList list)
{
return list.Cast<object>().Distinct(DistinctComparer.Instance).ToList();
}
/// <summary>
/// Determines if the given list contains the given item. This function searches through the sublists contained in it.
/// </summary>
/// <param name="list">List to search in.</param>
/// <param name="item">Item to look for.</param>
/// <returns name="bool">Whether list contains the given item.</returns>
/// <search>item,search,in,listcontains</search>
[IsVisibleInDynamoLibrary(true)]
public static bool Contains(IList list, [ArbitraryDimensionArrayImport] object item)
{
bool result = false;
foreach (var obj in list)
{
if (obj is IList) result = result || Contains((IList)obj, item);
}
// After checking all sublists, check if the current list contains the item
return result || (IndexInList(list, item) >= 0);
}
/// <summary>
/// Check if the items in the list are of the same type.
/// </summary>
/// <param name="list">List to be checked if it's homogeneous.</param>
/// <returns name="bool">Whether the list is homogeneous.</returns>
/// <search>homogeneous,allequal,same,type</search>
[IsVisibleInDynamoLibrary(true)]
public static bool IsHomogeneous(IList list)
{
if (list.Count > 0)
{
var firstItem = list[0];
foreach (var obj in list)
{
if (obj.GetType() != firstItem.GetType())
{
return false;
}
}
}
return true;
}
/// <summary>
/// Check if the number of items in all rows of the list are the same.
/// </summary>
/// <param name="list">List to be checked if the rows have the same number of items.</param>
/// <returns name="bool">Whether the list has the same number of items in all rows.</returns>
/// <search>rectangular,isrectangular,same,sublist,row</search>
[IsVisibleInDynamoLibrary(true)]
public static bool IsRectangular(IList list)
{
int count = -1;
if (list.Count <= 0) return false;
foreach (var obj in list)
{
if (!(obj is IList)) return false; // All items must be in a list in order to do a comparison
if (count == -1) count = ((IList)obj).Count; // If the count has not yet been initialized, assign the value
else if (count != ((IList)obj).Count) return false; // Otherwise, check if they have the same count. If not, return false
}
return true; //if all items have the same count
}
/// <summary>
/// Check if the items in the list have the same depth.
/// </summary>
/// <param name="list">List to be checked if the items have the same depth.</param>
/// <returns name="bool">Whether the depth of the list is uniform.</returns>
/// <search>depth,uniform,isuniformdepth,sublist,jagged</search>
[IsVisibleInDynamoLibrary(true)]
public static bool IsUniformDepth(IList list)
{
int depth = -1;
if (list.Count > 0) depth = GetDepth(list[0]);
foreach (var obj in list)
{
if (GetDepth(obj) != depth) return false;
}
return true;
}
/// <summary>
/// Returns a new list that includes objects in List1 but excludes objects in List2.
/// </summary>
/// <param name="list1">List of objects to be included in the new list.</param>
/// <param name="list2">List of objects to be excluded in the new list.</param>
/// <returns name="newList">The new list that contains objects in List1 but not in List2.</returns>
/// <search>difference,setdifference,set</search>
[IsVisibleInDynamoLibrary(true)]
public static IList SetDifference(IList<object> list1, IList<object> list2)
{
return Enumerable.Except(list1, list2).ToList();
}
/// <summary>
/// Returns a new list that includes objects that are present in both List1 and List2.
/// </summary>
/// <param name="list1">List of objects to be compared with list2.</param>
/// <param name="list2">List of objects to be compared with list1.</param>
/// <returns name="newList">The new list that contains objects that are in both List1 and List2.</returns>
/// <search>intersection,setintersection,set,overlap</search>
[IsVisibleInDynamoLibrary(true)]
public static IList SetIntersection(IList<object> list1, IList<object> list2)
{
return Enumerable.Intersect(list1, list2).ToList();
}
/// <summary>
/// Returns a new list that includes objects that are present in either List1 or List2.
/// </summary>
/// <param name="list1">List of objects to be included.</param>
/// <param name="list2">List of objects to be included to List1.</param>
/// <returns name="newList">The new list that contains objects that are either in List1 or List2.</returns>
/// <search>union,setunion,set</search>
[IsVisibleInDynamoLibrary(true)]
public static IList SetUnion(IList<object> list1, IList<object> list2)
{
return Enumerable.Union(list1, list2).ToList();
}
/// <summary>
/// Returns the index of the element in the given list.
/// </summary>
/// <param name="list">The list to find the element in.</param>
/// <param name="element">The element whose index is to be returned.</param>
/// <returns name="int">The index of the element in the list.</returns>
/// <search>index,indexof</search>
[IsVisibleInDynamoLibrary(true)]
public static int IndexOf(IList list, object element)
{
return list.IndexOf(element);
}
/// <summary>
/// Returns the number of false boolean values in the given list.
/// </summary>
/// <param name="list">The list find the false boolean values.</param>
/// <returns name="int">The number of false boolean values in the list.</returns>
/// <search>false,count</search>
[IsVisibleInDynamoLibrary(true)]
public static int CountFalse(IList list)
{
return CountBool(list, false);
}
/// <summary>
/// Returns the number of true boolean values in the given list.
/// </summary>
/// <param name="list">The list find the true boolean values.</param>
/// <returns name="int">The number of true boolean values in the list.</returns>
/// <search>true,count</search>
[IsVisibleInDynamoLibrary(true)]
public static int CountTrue(IList list)
{
return CountBool(list, true);
}
/// <summary>
/// Inserts an element into a list at specified index.
/// </summary>
/// <param name="list">The list the element will be inserted to.</param>
/// <param name="element">The element to be inserted.</param>
/// <param name="index">Specifies the location in the list of the element to be inserted.</param>
/// <returns name="list">The list with the element inserted.</returns>
/// <search>insert,add</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Insert(IList list, [ArbitraryDimensionArrayImport] object element, int index)
{
list.Insert(index, element);
return list;
}
/// <summary>
/// Reorders the input list based on the given list of indices.
/// </summary>
/// <param name="list">The list to be reordered.</param>
/// <param name="indices">The indices used to reorder the items in the list.</param>
/// <returns name="list">The reordered list.</returns>
/// <search>reorder,index,indices</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Reorder(IList list, IList indices)
{
// Note: slightly different behaviour from Builtin - invalid input indices will be ignored,
// and will return a list instead of null if the indices are invalid
List<object> newList = new List<object>();
for (int i = 0; i < indices.Count; i++)
{
int index;
if ((int.TryParse(indices[i].ToString(), out index) && (index >= 0) && (index < list.Count)))
{
newList.Add(list[index]);
}
}
return newList;
}
/// <summary>
/// Sorts a list by the items and return their indices.
/// </summary>
/// <param name="list">The list of items to be sorted.</param>
/// <returns name="newList">The indices of the items in the sorted list.</returns>
/// <search>sort,index,value</search>
[IsVisibleInDynamoLibrary(true)]
public static IEnumerable SortIndexByValue(List<double> list)
{
List<Tuple<int, double>> tupleList = new List<Tuple<int, double>>();
for (int i = 0; i < list.Count; i++)
{
tupleList.Add(new Tuple<int, double>(i, list[i]));
}
tupleList = tupleList.OrderBy(x => x.Item2).ToList();
IEnumerable<int> newList = tupleList.OrderBy(x => x.Item2).Select(y => y.Item1);
return newList;
}
/// <summary>
/// Returns multidimensional list according the rank given.
/// </summary>
/// <param name="list">The list whose depth is to be normalized according to the rank.</param>
/// <param name="rank">The rank the list is to be normalized to. Default value is 1.</param>
/// <returns name="list">The list with the normalized rank.</returns>
/// <search>depth,normalize</search>
[IsVisibleInDynamoLibrary(true)]
public static IList NormalizeDepth(IList list, int rank = 1)
{
if (rank <= 1)
{
return Flatten(list);
}
else
{
for (int i = 0; i < list.Count; i++)
{
if (list[i] is IList)
{
list[i] = NormalizeDepth((IList)list[i], rank - 1);
}
else
{
list[i] = IncreaseDepth(new List<object>() { list[i] }, rank - 1);
}
}
}
return list;
}
/// <summary>
/// Creates a new list containing the items of the given list but in reverse order.
/// </summary>
/// <param name="list">List to be reversed.</param>
/// <returns name="list">New list.</returns>
/// <search>flip,listcontains</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Reverse(IList list)
{
return list.Cast<object>().Reverse().ToList();
}
/// <summary>
/// Creates a new list containing the given items.
/// </summary>
/// <param name="items">Items to be stored in the new list.</param>
[IsVisibleInDynamoLibrary(true)]
public static IList __Create(IList items)
{
return items;
}
/// <summary>
/// Build sublists from a list using DesignScript range syntax.
/// </summary>
/// <param name="list">The list from which to create sublists.</param>
/// <param name="ranges">
/// The index ranges of the sublist elements.
/// Ex. \"{0..3,5,2}\"
/// </param>
/// <param name="offset">
/// The offset to apply to the sublist.
/// Ex. the range \"0..3\" with an offset of 2 will yield
/// {0,1,2,3}{2,3,4,5}{4,5,6,7}...
/// </param>
/// <returns name="lists">Sublists of the given list.</returns>
/// <search>sublists,build sublists,subset,</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Sublists(IList list, IList ranges, int offset)
{
var result = new ArrayList();
int len = list.Count;
if (offset <= 0)
throw new ArgumentException("Must be greater than zero.", "offset");
for (int start = 0; start < len; start += offset)
{
var row = new List<object>();
foreach (object item in ranges)
{
List<int> subrange;
if (item is ICollection)
subrange = ((IList)item).Cast<int>().Select(Convert.ToInt32).ToList();
else
subrange = new List<int> { Convert.ToInt32(item) };
row.AddRange(
subrange.Where(idx => start + idx < len).Select(idx => list[start + idx]));
}
if (row.Count > 0)
result.Add(row);
}
return result;
}
/// <summary>
/// Sorts a list using the built-in natural ordering.
/// </summary>
/// <param name="list">List to be sorted.</param>
/// <returns name="list">Sorted list.</returns>
/// <search>sort,order,sorted</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Sort(IEnumerable<object> list)
{
return list.OrderBy(x => x, new ObjectComparer()).ToList();
}
/// <summary>
/// Returns the minimum value from a list.
/// </summary>
/// <param name="list">List to take the minimum value from.</param>
/// <returns name="min">Minimum value from the list.</returns>
/// <search>least,smallest,find min</search>
[IsVisibleInDynamoLibrary(true)]
public static object MinimumItem(IEnumerable<object> list)
{
return list.Min<object, object>(DoubleConverter);
}
/// <summary>
/// Returns the maximum value from a list.
/// </summary>
/// <param name="list">List to take the maximum value from.</param>
/// <returns name="max">Maximum value from the list.</returns>
/// <search>greatest,largest,biggest,find max</search>
[IsVisibleInDynamoLibrary(true)]
public static object MaximumItem(IEnumerable<object> list)
{
return list.Max<object, object>(DoubleConverter);
}
/// <summary>
/// Filters a sequence by looking up corresponding indices in a separate list of
/// booleans.
/// </summary>
/// <param name="list">List to filter.</param>
/// <param name="mask">List of booleans representing a mask.</param>
/// <returns name="in">Items whose mask index is true.</returns>
/// <returns name="out">Items whose mask index is false.</returns>
/// <search>filter,in,out,mask,dispatch,bool filter,boolfilter,bool filter</search>
[MultiReturn(new[] { "in", "out" })]
[IsVisibleInDynamoLibrary(true)]
public static Dictionary<string, object> FilterByBoolMask(IList list, IList mask)
{
Tuple<ArrayList, ArrayList> result = FilterByMaskHelper(
list.Cast<object>(),
mask.Cast<object>());
return new Dictionary<string, object>
{
{ "in", result.Item1 },
{ "out", result.Item2 }
};
}
/// <summary>
/// Given a list, produces the first item in the list, and a new list containing all items
/// except the first.
/// </summary>
/// <param name="list">List to be split.</param>
/// <returns name="first">First item in the list.</returns>
/// <returns name="rest">Rest of the list.</returns>
/// <search>first,rest,list split,listcontains</search>
[MultiReturn(new[] { "first", "rest" })]
[IsVisibleInDynamoLibrary(true)]
public static IDictionary Deconstruct(IList list)
{
return new Dictionary<string, object>
{
{ "first", list[0] },
{ "rest", list.Cast<object>().Skip(1).ToList() }
};
}
/// <summary>
/// Sort list based on its keys
/// </summary>
/// <param name="list">list to be sorted</param>
/// <param name="keys">list of keys</param>
/// <returns name="sorted list">sorted list</returns>
/// <returns name="sorted keys">sorted keys</returns>
/// <search>sort;key</search>
[MultiReturn(new[] { "sorted list", "sorted keys" })]
[IsVisibleInDynamoLibrary(true)]
public static IDictionary SortByKey(IList list, IList keys)
{
if (list == null || keys == null)
return null;
var containsSublists = keys.Cast<object>().Any(key => key is IList || key is ICollection);
if (containsSublists)
{
throw new ArgumentException(Resources.InvalidKeysErrorMessage);
}
if (list.Count != keys.Count)
{
throw new ArgumentException(Resources.InvalidKeysLenghtErrorMessage);
}
var pairs = list.Cast<object>()
.Zip(keys.Cast<object>(), (item, key) => new { item, key });
var numberKeyPairs = pairs.Where(pair => pair.key is double || pair.key is int || pair.key is float);
// We don't use Except, because Except doesn't return duplicates.
var keyPairs = pairs.Where(
pair =>
!numberKeyPairs.Any(
numberPair => numberPair.item == pair.item && numberPair.key == pair.key));
// Sort.
numberKeyPairs = numberKeyPairs.OrderBy(pair => Convert.ToDouble(pair.key));
keyPairs = keyPairs.OrderBy(pair => pair.key);
// First items with number keys, then items with letter keys.
var sortedPairs = numberKeyPairs.Concat(keyPairs);
var sortedList = sortedPairs.Select(x => x.item).ToList();
var sortedKeys = sortedPairs.Select(x => x.key).ToList();
return new Dictionary<object, object>
{
{ "sorted list", sortedList },
{ "sorted keys", sortedKeys }
};
}
/// <summary>
/// Group items into sub-lists based on their like key values
/// </summary>
/// <param name="list">List of items to group as sublists</param>
/// <param name="keys">Key values, one per item in the input list, used for grouping the items</param>
/// <returns name="groups">list of sublists, with items grouped by like key values</returns>
/// <returns name="unique keys">key value corresponding to each group</returns>
/// <search>list;group;groupbykey;</search>
[MultiReturn(new[] { "groups", "unique keys" })]
[IsVisibleInDynamoLibrary(true)]
public static IDictionary GroupByKey(IList list, IList keys)
{
if (list.Count != keys.Count)
{
throw new ArgumentException(Resources.InvalidKeysLenghtErrorMessage);
}
var containsSublists = keys.Cast<object>().Any(key => key is IList || key is ICollection);
if (containsSublists)
{
throw new ArgumentException(Resources.InvalidKeysErrorMessage);
}
var groups =
list.Cast<object>().Zip(keys.Cast<object>(), (item, key) => new { item, key })
.GroupBy(x => x.key)
.Select(x => x.Select(y => y.item).ToList());
var uniqueItems = keys.Cast<object>().Distinct().ToList();
return new Dictionary<object, object>
{
{ "groups", groups },
{ "unique keys", uniqueItems }
};
}
/// <summary>
/// Adds an item to the beginning of a list.
/// </summary>
/// <param name="item">Item to be added. Item could be an object or a list.</param>
/// <param name="list">List to add on to.</param>
/// <returns name="list">New list.</returns>
/// <search>insert,add,item,front,start,begin</search>
[IsVisibleInDynamoLibrary(true)]
public static IList AddItemToFront([ArbitraryDimensionArrayImport] object item, IList list)
{
var newList = new ArrayList { item };
newList.AddRange(list);
return newList;
}
/// <summary>
/// Adds an item to the end of a list.
/// </summary>
/// <param name="item">Item to be added.Item could be an object or a list.</param>
/// <param name="list">List to add on to.</param>
/// <search>insert,add,item,end</search>
[IsVisibleInDynamoLibrary(true)]
public static IList AddItemToEnd([ArbitraryDimensionArrayImport] object item, IList list)
{
return new ArrayList(list) //Clone original list
{
item //Add item to the end of cloned list.
};
}
/// <summary>
/// Fetches an amount of items from the start of the list.
/// </summary>
/// <param name="list">List to take from.</param>
/// <param name="amount">
/// Amount of items to take. If negative, items are taken from the end of the list.
/// </param>
/// <returns name="list">List of extracted items.</returns>
/// <search>get,sub,sublist,extract</search>
[IsVisibleInDynamoLibrary(true)]
public static IList TakeItems(IList list, int amount)
{
IEnumerable<object> genList = list.Cast<object>();
return (amount < 0 ? genList.Skip(list.Count + amount) : genList.Take(amount)).ToList();
}
/// <summary>
/// Removes an amount of items from the start of the list. If the amount is a negative value,
/// items are removed from the end of the list.
/// </summary>
/// <param name="list">List to remove items from.</param>
/// <param name="amount">
/// Amount of items to remove. If negative, items are removed from the end of the list.
/// </param>
/// <returns name="list">List of remaining items.</returns>
/// <search>drop,remove,shorten</search>
[IsVisibleInDynamoLibrary(true)]
public static IList DropItems(IList list, int amount)
{
IEnumerable<object> genList = list.Cast<object>();
return (amount < 0 ? genList.Take(list.Count + amount) : genList.Skip(amount)).ToList();
}
/// <summary>
/// Shifts indices in the list to the right by the given amount.
/// </summary>
/// <param name="list">List to be shifted.</param>
/// <param name="amount">
/// Amount to shift indices by. If negative, indices will be shifted to the left.
/// </param>
/// <returns name="list">Shifted list.</returns>
/// <search>shift,offset</search>
[IsVisibleInDynamoLibrary(true)]
public static IList ShiftIndices(IList list, int amount)
{
var count = list.Count;
if (count > 0 && System.Math.Abs(amount) > count)
{
amount = amount % count;
}
if (amount == 0) return list;
IEnumerable<object> genList = list.Cast<object>();
return
(amount < 0
? genList.Skip(-amount).Concat(genList.Take(-amount))
: genList.Skip(list.Count - amount).Concat(genList.Take(list.Count - amount)))
.ToList();
}
/// <summary>
/// Returns an item from the given list that's located at the specified index.
/// </summary>
/// <param name="list">List to fetch an item from.</param>
/// <param name="index">Index of the item to be fetched.</param>
/// <returns name="item">Item in the list at the given index.</returns>
/// <search>get,item,index,fetch,at,getfrom,get from,extract</search>
[IsVisibleInDynamoLibrary(true)]
public static object GetItemAtIndex(IList list, int index)
{
return list[index];
}
/// <summary>
/// Replace an item from the given list that's located at the specified index.
/// </summary>
/// <param name="list">List to replace an item in.</param>
/// <param name="index">Index of the item to be replaced.</param>
/// <param name="item">The item to insert.</param>
/// <returns name="list">A new list with the item replaced.</returns>
/// <search>replace,switch</search>
[IsVisibleInDynamoLibrary(true)]
public static IList ReplaceItemAtIndex(IList list, int index, [ArbitraryDimensionArrayImport] object item)
{
if (index < 0)
{
index = list.Count + index;
}
if (index >= list.Count || index < 0)
{
throw new IndexOutOfRangeException();
}
// copy the list, insert and return
var newList = new ArrayList(list);
newList[index] = item;
return newList;
}
/// <summary>
/// Returns a single sub-list from the given list, based on starting index, ending index,
/// and a step amount.
/// </summary>
/// <param name="list">List to take a slice of.</param>
/// <param name="start">Index to start the slice from.</param>
/// <param name="end">Index to end the slice at.</param>
/// <param name="step">
/// Amount the indices of the items are separate by in the original list.
/// </param>
/// <returns name="items">Items in the slice of the given list.</returns>
/// <search>list,sub,sublist,subrange,get sublist</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Slice(IList list, int? start = null, int? end = null, int step = 1)
{
if (step == 0)
throw new ArgumentException("Cannot slice a list with step of 0.", @"step");
int _start = start ?? (step < 0 ? -1 : 0);
int _end = end ?? (step < 0 ? -list.Count - 1 : list.Count);
_start = _start >= 0 ? _start : _start + list.Count;
if (_start < 0)
_start = 0;
_end = _end >= 0 ? _end : _end + list.Count;
if (_end > list.Count)
_end = list.Count;
IList result = new ArrayList();
if (step > 0)
{
if (_start > _end)
return result;
for (int i = _start; i < _end; i += step)
result.Add(list[i]);
}
else
{
if (_end > _start)
return result;
for (int i = _start; i > _end; i += step)
result.Add(list[i]);
}
return result;
}
/// <summary>
/// Removes an item from the given list at the specified index.
/// </summary>
/// <param name="list">List to remove an item or items from.</param>
/// <param name="indices">Index or indices of the item(s) to be removed.</param>
/// <returns name="list">List with items removed.</returns>
/// <search>index,indices,cull,remove,item</search>
[IsVisibleInDynamoLibrary(true)]
public static IList RemoveItemAtIndex(IList list, int[] indices)
{
return list.Cast<object>().Where((_, i) => !indices.Contains(i)).ToList();
}
/// <summary>
/// Removes items from the given list at indices that are multiples
/// of the given value, after the given offset.
/// </summary>
/// <param name="list">List to remove items from/</param>
/// <param name="n">Indices that are multiples of this argument will be removed.</param>
/// <param name="offset">
/// Amount of items to be ignored from the start of the list.
/// </param>
/// <returns name="list">List with items removed.</returns>
/// <search>nth,remove,cull,every</search>
[IsVisibleInDynamoLibrary(true)]
public static IList DropEveryNthItem(IList list, int n, int offset = 0)
{
return list.Cast<object>().Where((_, i) => (i + 1 - offset)%n != 0).ToList();
}
/// <summary>
/// Fetches items from the given list at indices that are multiples
/// of the given value, after the given offset.
/// </summary>
/// <param name="list">List to take items from.</param>
/// <param name="n">
/// Indices that are multiples of this number (after the offset)
/// will be fetched.
/// </param>
/// <param name="offset">
/// Amount of items to be ignored from the start of the list.
/// </param>
/// <returns name="items">Items from the list.</returns>
/// <search>fetch,take,every,nth</search>
[IsVisibleInDynamoLibrary(true)]
public static IList TakeEveryNthItem(IList list, int n, int offset = 0)
{
return list.Cast<object>().Where((_, i) => (i + 1 - offset)%n == 0).ToList();
}
/// <summary>
/// Determines if the given list is empty.
/// </summary>
/// <param name="list">List to check for items.</param>
/// <returns name="bool">Whether the list is empty.</returns>
/// <search>test,is,empty,null,count</search>
[IsVisibleInDynamoLibrary(true)]
public static bool IsEmpty(IList list)
{
return list.Count == 0;
}
/// <summary>
/// Determines if all items in the given list is a boolean and has a true value.
/// </summary>
/// <param name="list">List to be checked on whether all items are true.</param>
/// <returns name="bool">Whether all items are true.</returns>
/// <search>test,all,true,istrue</search>
[IsVisibleInDynamoLibrary(true)]
public static bool AllTrue(IList list)
{
bool result = true;
foreach (var obj in list)
{
if (obj is IList)
{
result = result && AllTrue((IList)obj);
}
else
{
if ((obj is bool) && (bool)obj) continue;
else return false;
}
}
return result;
}
/// <summary>
/// Determines if all items in the given list is a boolean and has a false value.
/// </summary>
/// <param name="list">List to be checked on whether all items are false.</param>
/// <returns name="bool">Whether all items are false.</returns>
/// <search>test,all,false,isfalse</search>
[IsVisibleInDynamoLibrary(true)]
public static bool AllFalse(IList list)
{
bool result = true;
foreach (var obj in list)
{
if (obj is IList)
{
result = result && AllFalse((IList)obj);
}
else
{
if ((obj is bool) && !(bool)obj) continue;
else return false;
}
}
return result;
}
/// <summary>
/// Returns the number of items stored in the given list.
/// </summary>
/// <param name="list">List to get the item count of.</param>
/// <returns name="count">List length.</returns>
/// <search>listlength,list length,count,size,sizeof</search>
[IsVisibleInDynamoLibrary(true)]
public static int Count(IList list)
{
return list.Count;
}
/// <summary>
/// Concatenates all given lists into a single list.
/// </summary>
/// <param name="lists">Lists to join into one.</param>
/// <returns name="list">Joined list.</returns>
/// <search>join lists,merge,concatenate</search>
[IsLacingDisabled]
[IsVisibleInDynamoLibrary(true)]
public static IList Join(params IList[] lists)
{
var result = new ArrayList();
foreach (IList list in lists)
result.AddRange(list);
return result;
}
/// <summary>
/// Returns the first item in a list.
/// </summary>
/// <param name="list">List to get the first item from.</param>
/// <returns name="item">First item in the list.</returns>
/// <search>get,fetch,first,item,start</search>
[IsVisibleInDynamoLibrary(true)]
public static object FirstItem(IList list)
{
return list[0];
}
/// <summary>
/// Removes the first item from the given list.
/// </summary>
/// <param name="list">List to get the rest of.</param>
/// <returns name="rest">Rest of the list.</returns>
/// <search>get,fetch,rest,end,rest of list</search>
[IsVisibleInDynamoLibrary(true)]
public static IList RestOfItems(IList list)
{
return list.Cast<object>().Skip(1).ToList();
}
/// <summary>
/// Chop a list into a set of consecutive sublists with the specified lengths. List division begins at the top of the list.
/// </summary>
/// <param name="list">List to chop into sublists</param>
/// <param name="lengths">Lengths of consecutive sublists to be created from the input list</param>
/// <returns name="lists">Sublists created from the list</returns>
/// <search>sublists,build sublists,slices,partitions,cut,listcontains,chop</search>
[IsVisibleInDynamoLibrary(true)]
public static IList Chop(IList list, List<int> lengths)
{
var finalList = new ArrayList();
var currList = new ArrayList();
int count = 0;
int lengthIndex = 0;
// If there are not any lengths more than 0,
// we return incoming list.
if (lengths.All(x => x <= 0))
{
return list;
}
foreach (object obj in list)
{
// If number of items in current list equals length in list of lengths,
// we should add current list in final list.
// Or if length in list of lengths <= 0, we should process this length and move further.
if (count == lengths[lengthIndex] || lengths[lengthIndex] <= 0)
{
finalList.Add(currList);
currList = new ArrayList();
if (lengthIndex < lengths.Count - 1)
{
lengthIndex++;
}
count = 0;
}
currList.Add(obj);
count++;
}
if (currList.Count > 0)
finalList.Add(currList);
return finalList;
}
/// <summary>
/// List elements along each diagonal in the matrix from the top left to the lower right.
/// </summary>
/// <param name="list">A flat list</param>
/// <param name="subLength">Length of each new sub-list.</param>
/// <returns name="diagonals">Lists of elements along matrix diagonals.</returns>
/// <search>diagonal,right,matrix,get diagonals,diagonal sublists</search>
[IsVisibleInDynamoLibrary(true)]
public static IList DiagonalRight([ArbitraryDimensionArrayImport] IList list, int subLength)
{
object[] flatList;
try
{
flatList = list.Cast<ArrayList>().SelectMany(i => i.Cast<object>()).ToArray();
}
catch
{
flatList = list.Cast<object>().ToArray();
}
if (flatList.Count() < subLength)
return list;
var finalList = new List<List<object>>();
var startIndices = new List<int>();
//get indices along 'side' of array
for (int i = subLength; i < flatList.Count(); i += subLength)
startIndices.Add(i);
startIndices.Reverse();
//get indices along 'top' of array
for (int i = 0; i < subLength; i++)
startIndices.Add(i);
foreach (int start in startIndices)
{
int index = start;
var currList = new List<object>();
while (index < flatList.Count())
{
var currentRow = (int)System.Math.Ceiling((index + 1)/(double)subLength);
currList.Add(flatList[index]);
index += subLength + 1;
//ensure we are skipping a row to get the next index
var nextRow = (int)System.Math.Ceiling((index + 1)/(double)subLength);
if (nextRow > currentRow + 1 || nextRow == currentRow)
break;
}
finalList.Add(currList);
}
return finalList;
}
/// <summary>
/// List elements along each diagonal in the matrix from the top right to the lower left.
/// </summary>
/// <param name="list">A flat list.</param>
/// <param name="rowLength">Length of each new sib-list.</param>
/// <returns name="diagonals">Lists of elements along matrix diagonals.</returns>
/// <search>diagonal,left,matrix,get diagonals,diagonal sublists</search>
[IsVisibleInDynamoLibrary(true)]
public static IList DiagonalLeft(IList list, int rowLength)
{
object[] flatList;
try
{
flatList = list.Cast<ArrayList>().SelectMany(i => i.Cast<object>()).ToArray();