public static Student[] AddIndices(this Student[] incomingArray, Student newItem) { Student[] _temp = new Student[incomingArray.Length]; _temp[incomingArray.Length] = newItem; return _temp; }
/// <summary> /// Remove an element from an array, old school style! /// </summary> /// <param name="incomingArray"></param> /// <param name="Removeindex"></param> /// <returns></returns> public static Student[] RemoveIndices(this Student[] incomingArray, int Removeindex) { Student[] _temp = new Student[incomingArray.Length - 1]; int i = 0; int j = 0; while (i < incomingArray.Length) { if (i != Removeindex) { _temp[j] = incomingArray[i]; //you need a second index because your going to be sending back a shorter array and their length is immutable j++; } i++; } return _temp; }
/// <summary> /// A classic sort of a problem really. Given a list, can you randomly shuffle it into an array but be sure that the array is full? /// My first approach, commented out, does not guarantee this at all! /// </summary> /// <param name="intake"></param> /// <returns></returns> private List<Student> shuffleStudents(List<Student> intake) { Random ind = new Random(); var inputStudents = intake.ToArray(); Student[] students = new Student[intake.Count]; int s = 0; while (students.Any(x => x == null) && inputStudents.Length > 0) { int r = ind.Next(0, inputStudents.Length); if (students[r] == null) { students[r] = inputStudents[s]; //do this here so I can get s = 0 in the array } else { List<int> nulls = new List<int>(); for (int _i = 0; _i < inputStudents.Count(); _i++) if (students[_i] == null) nulls.Add(_i); //get a list of null indices if (nulls.Count() > 0) students[nulls.First()] = inputStudents[s]; //fill up the holes } s++; s = s < inputStudents.Length ? s : 0; //increment the input index but don't go outside the bounds of the array! } return students.ToList(); }