I have a "Element" class with a "Index" property which is used for sorting a list of elements. When i'm adding elements to the list I want to spread out the new elements evenly according to existing elements in the list.
This means if I have 6 elements and want to add 3 elements the result should look like the image below:
The problem I have with my code (See below) so far is it uses the wrong index, so if I have 2 existing elements and add 9 elements, the last element index is 18 which I don't really understand.
public List<Element> AddElements()
{
// The elements are inserted before this
List<Element> existingElements = new List<Element>();
List<Element> elementsToAdd = new List<Element>();
int elementsLeft = 1;
foreach (Element element in elementsToAdd)
{
// Generate the next index
int nextIndex = 1;
// Only proceed if any elements exists
if (existingElements.Count > 0)
{
// divisonResult = 12 / 4 = 3
double divisonResult = Math.Floor(Convert.ToDouble(existingElements.Count) / Convert.ToDouble(elementsToAdd.Count));
// modulusResult = 12 % 2 = 0
double modulusResult = Convert.ToDouble(existingElements.Count) % Convert.ToDouble(elementsToAdd.Count);
// NextPosition = (3 + 1) * 1 = 4
// NextPosition = (3 + 1) * 2 = 8
// NextPosition = (3 + 1) * 3 = 12
// NextPosition = (3 + 1) * 4 = 16
if (modulusResult <= 0 && elementsToAdd.Count > 1)
nextIndex = Convert.ToInt16(divisonResult) * elementsLeft;
else
nextIndex = (Convert.ToInt16(divisonResult) + 1) * elementsLeft;
elementsLeft++;
// Move existing elements
var elementsToBeMoved = existingElements.Where(elementQuery => elementQuery.Index >= nextIndex);
foreach (Element elementToBeMoved in elementsToBeMoved)
{
elementToBeMoved.Index++;
}
}
// Add element to existing elements
existingElements.Add(new Element { Index = nextIndex });
}
// Return new list
return existingElements;
}