简体   繁体   中英

In what order are List<T> items added and retrieved?

So, I have this problem: I've been adding content from textboxes, on different panels of the WinForm, to different lists like this:

List<String> priceList= new List<String>();
foreach (Control c in pricePanel.Controls)
{
    if (c is TextBox)
    {
        priceList.Add(c.Text);
    }
}
List<String> numberItemsList= new List<String>();
foreach (Control c in numberItemsPanel.Controls)
{
    if (c is TextBox)
    {
        numberItemsList.Add(c.Text);
     }
 }
List<String> productsList = new List<String>();
foreach (Control control in productsPanel.Controls)
{
   if (control is ComboBox)
   {
       foreach (ComboBox c in productsPanel.Controls)
       {
            productsList.Add(c.SelectedValue.ToString());
       }
   }
}

Now, I understand that the List<T> class returns items on the same order they were inserted, but when I insert the content of the lists on a sql table, they're not in the same order that the textboxes are on the winform. To give an example, the values from the first panel of textboxes were inserted in this order:
1
2
3
5
4
whilst the values from the second panel (same number of textboxes and same layout as the first) were inserted like this:
4
2
1
5
3
To get the values from the lists I'm simply looping through them: for (int i=0; i<priceList.Count; i++) . I believe the problem is when I get the values from the textboxes, what I want to know is if there's a way to match the order of the textboxes with the order in which the items are inserted on the list. If you have a better way to do this instead of the mess I did, feel free to share. Thank you!

Indeed the order of the elements in your list is the order you added them. As long as you add them by using Add() .

When storing them in an sql table they get added to this table in no specific order at all, for most databases do not preserve this order. If you definitely need them to be in the order you added them to your table you could add a timestamp to your tuples, when adding them.

insert into myTable (name, addedAt) values ("MyValue", now());

Retrieve them ordered by this timestamp via

select Name from myTable order by addedAt;

The above is just an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM