简体   繁体   English

列表按什么顺序 <T> 添加和检索项目?

[英]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: 所以,我有一个问题:我一直在将文本框的内容添加到WinForm的不同面板上,如下所示:

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. 现在,我了解到List<T>类按插入顺序返回项目,但是当我在sql表中插入列表内容时,它们的顺序与winform上文本框的顺序不同。 To give an example, the values from the first panel of textboxes were inserted in this order: 举个例子,第一个文本框面板中的值按以下顺序插入:
1 1
2 2
3 3
5
4 4
whilst the values from the second panel (same number of textboxes and same layout as the first) were inserted like this: 同时插入第二个面板中的值(与第一个面板相同的文本框数量和布局),如下所示:
4 4
2 2
1 1
5
3 3
To get the values from the lists I'm simply looping through them: for (int i=0; i<priceList.Count; i++) . 为了从列表中获取值,我只是遍历它们: 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() . 只要使用Add()将它们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. 将它们存储在sql表中时,它们根本没有特定的顺序添加到该表中,因为大多数数据库都不保留此顺序。 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. 以上仅是示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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