I have an array like Original = {1, 2, 3, 6, 7, 8, 9, 10, 12}
. After removing some elements like Delete = {6, 7}
from it, I want to get n
sequential numbers which are not in the array, like IDs = {4, 5, 6, 7, 11, 13, 14, ..., n}
.
After getting the numbers I want the original array to be changed to the updated array.
public static ushort GetNextID(ref List<ushort> Updating)
{
for (var i = 0; i < Updating.Count; i++)
{
if (Updating[i] != i + 1)
{
Updating.Insert(i, Convert.ToUInt16(i + 1));
return Convert.ToUInt16(i + 1);
}
}
Updating.Add(Convert.ToUInt16(Updating.Last() + 1));
return Convert.ToUInt16(Updating.Last() + 1);
}
public static ushort[] GetNextIDs(ref List<ushort> Updating, ushort Count)
{
List<ushort> IDs = new List<ushort>();
for (var t = 0; t < Count; t++) IDs.Add(GetNextID(ref Updating));
return IDs.ToArray();
}
static void Main(string[] args)
{
IEnumerable<ushort> Original = new ushort[] { 1, 2, 3, 4, 5, 6, 7, 9, 10 };
IEnumerable<ushort> Delete = new ushort[] { 4, 5, 6 };
var Updating = Original.Except(Delete).ToList();
// Expected: 4, 5, 6, 8, 11, 12, 13, 14
// Outputs: 4, 5, 6, 8, 12, 13, 14, 15
foreach (var id in GetNextIDs(ref Updating, 8)) Console.WriteLine(id);
Console.WriteLine();
// 1, 2, 3, (4, 5, 6), 7, (8), 9, 10, (11, 12, 13, 14)
foreach (var i in Updating) Console.WriteLine(i);
Original = Updating;
Console.ReadKey();
}
I'm using ref
s for performance but I'm not sure if it does any good.