Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find an implementation of the query pattern Error

Tags:

c#

linq

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?

like image 980
P.Brian.Mackey Avatar asked Nov 29 '22 03:11

P.Brian.Mackey


2 Answers

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
like image 22
Rich Avatar answered Jan 27 '23 12:01

Rich


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>()...

like image 198
Jon Skeet Avatar answered Jan 27 '23 12:01

Jon Skeet