Can't convert ListBox.ObjectCollection to a (typed) array

后端 未结 2 373
逝去的感伤
逝去的感伤 2021-01-04 20:43

I want to convert the items to a String array or the type that I used to fill the ListBox.DataSource. The type has overridden ToString() but I can\'t seems to get it convert

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 21:03

    string[] a = ListBox1.Items.Cast().ToArray();
    

    Of course, if all you plan to do with a is iterate over it, you don't have to call ToArray(). You can directly use the IEnumerable returned from Cast(), e.g.:

    foreach (var s in ListBox1.Items.Cast()) {
        do_something_with(s);
    }
    

    Or, if you have some way to convert strings to Contacts, you can do something like this:

    IEnumerable c = ListBox1.Items.Cast().Select(s => StringToContact(s));
    

提交回复
热议问题