I have a Windows.Forms.FlowLayoutPanel
that is being filled at runtime with controls of the type MasterMeter
(and controls inheriting from MasterMeter). This is your standard Usercontrol
. Each of those controls has a property ErrorTime
. This value keeps the duration of the current error or alert.
Datetime? ErrorTime {get; set;}
I'm currently trying to order the controls using the bubblesort-method
based on the duration of the error (descending). Right now I was wondering is there a faster/more performant/more reliable way to do this?
If not, is there another container i could be using? It needs to have the following caracteristics:
Current Code (that won't sort)
I'm using a 1D-Array to keep it simple (in reality its a jagged Array).
Note: The possibilty of NULL
values
MasterMeter[] meterList = {new MasterMeter() { ErrorTime = null },
new MasterMeter() { ErrorTime = DateTime.Now },
new MasterMeter() { ErrorTime = DateTime.Now.AddDays(-10) },
new MasterMeter() { ErrorTime = DateTime.Now.AddDays(37) },
new MasterMeter() { ErrorTime = DateTime.Now.AddDays(53) },
new MasterMeter() { ErrorTime = DateTime.Now.AddDays(3) },
new MasterMeter() { ErrorTime = null },
new MasterMeter() { ErrorTime = DateTime.Now.AddDays(-17) },
new MasterMeter() { ErrorTime = DateTime.Now.AddDays(-10) },
new MasterMeter() { ErrorTime = null }
};
I'm Bubblesorting
as follows:
for (int outer = 0; outer < meterList.Count(); outer++)
{
for (int inner = 0; inner < (meterList.Count() - 1); inner++)
{
if (meterList[inner].ErrorTime > meterList[inner + 1].ErrorTime)
{
var temp = meterList[inner + 1];
meterList[inner + 1] = meterList[inner];
meterList[inner] = temp;
}
}
}
My ouput result (Using Console.Writeline
):
foreach (MasterMeter meterlist in meterList)
{
Console.WriteLine(meterlist.ErrorTime);
}
Console.ReadLine();
But my array still isn't sorted. What is going wrong here?
You have to decide what to do with those null values in your list since it does interfere with your bubble sort:
if (!meterList[inner].ErrorTime.HasValue ||
meterList[inner].ErrorTime > meterList[inner + 1].ErrorTime) {
As far as re-ordering the controls in the FlowLayoutPanel, that code was missing from your post, but in general, you would use the FlowLayoutPanel.Controls.SetChildIndex
method to re-order your controls.