4

Given

   var selectedItems = listBoxControl1.SelectedItems;
   var selectedItemsList = (from i in selectedItems
                             select i).ToList();

I receive Error

Could not find an implementation of the query pattern for source type 'DevExpress.XtraEditors.BaseListBoxControl.SelectedItemCollection'. 'Select' not found. Consider explicitly specifying the type of the range variable 'i'.

using system.LINQ Done

I can use foreach so it must implement IEnumerable. I prefer to use LINQ over foreach to gather each string, if possible.

I want to take the ToString() values for each SelectedItem in the list box control and stick them in a List<string>. How can I do it?

ColinE
  • 68,894
  • 15
  • 164
  • 232
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • 1
    for a foreach to work the type of the object after the keyword in simply needs to have a mthod called GetEnumerator() which in turn returns an object of a type that has a MoveNext() method and a Current property. It does **not** need to implement IEnumerable – Rune FS Mar 21 '12 at 14:05

3 Answers3

14

I can use foreach so it must implement IEnumerable.

That's not actually true, but it's irrelevant here. It does implement IEnumerable, but not IEnumerable<T> which is what LINQ works over.

What's actually in the list? If it's already strings, you could use:

var selectedItemsList = selectedItems.Cast<string>().ToList();

Or if it's "any objects" and you want to call ToString you can use:

var selectedItemsList = selectedItems.Cast<object>()
                                     .Select(x => x.ToString())
                                     .ToList();

Note that the call to Cast is why the error message suggested using an explicitly typed range variable - a query expression starting with from Foo foo in bar will be converted to bar.Cast<Foo>()...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What is required to implement foreach? – P.Brian.Mackey Mar 21 '12 at 14:04
  • 1
    @P.Brian.Mackey: A method called `GetEnumerator()` which is declared to return a type with suitable `MoveNext()` and `Current` members. It doesn't have to implement `IEnumerable`. Using a type with a `Current` property of (say) `int` was a way to avoid boxing while iterating before generics. – Jon Skeet Mar 21 '12 at 14:06
  • just login to up cast this – Tawfik Khalifeh Jul 12 '13 at 15:48
7

For LINQ to work, you need an IEnumerable<T>, straight IEnumerable isn't enough. Try:

var selectedItems = listboxControl1.SelectedItems.Cast<T> //where T is the actual type of the item
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
Rich
  • 2,076
  • 1
  • 15
  • 16
1

Try just

var result = listBoxControl1.SelectedItems.Cast<MyItemType>().ToList();
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188