Casting an Item Collection from a listbox to a generic list

前端 未结 3 506
情歌与酒
情歌与酒 2020-12-03 09:41

I want to find a better way of populating a generic list from a checkedlistbox in c#.

I can do the following easily enough:

List selec         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 10:20

    This is not exactly the answer to your requirement, but posting a more general answer. You could do it in a variety of ways:

    1)

    T[] items = new T[lb.Items.Count];
    lb.Items.CopyTo(items, 0);
    var lst = new List(items);
    

    2) looping and adding using foreach as you mentioned.

    3) using Linq

    var lst = lb.Items.Cast().ToList();
    

    4) or

    var lst = lb.Items.OfType().ToList();
    

    When I did some performance testing like below, I found copying to array method the fastest while the Linq methods slower. Of course in real world scenarios these wouldnt matter. I prefer the 3rd method (Linq) for readability.

    DateTime d = DateTime.Now;
    for (int i = 0; i < 10000; i++)
    {
        Action();
    }
    MessageBox.Show((DateTime.Now - d).TotalMilliseconds.ToString());
    

    For an iteration of 10000 times run multiple times with about 300 items in list box,

    1) ~100ms

    2) ~150ms

    3) ~250ms

    4) ~260ms

提交回复
热议问题