C# – Why can’t I use a Linq query on a Visio Masters collection

clinq

I am trying to do the following Linq query on a Visio Masters collection:

List<string> allMasterNames = (from master in myStencil.Masters select master.NameU).ToList<string>

I get the following error:

Could not find an implementation of
the query pattern for source type
'Microsoft.Office.Interop.Visio.Masters'.
'Select' not found. Consider
explicitly specifying the type of the
range variable 'master'.

From reading around this error seems to occur when the queried object does not implement IEnumerable<T> or IQueryable<T>. Is that the case here, or is it something else?

Best Answer

Yes, it is because it's not IEnumerable<T>, IQueryable<T> and it doesn't have its own custom Select method written.

Contary to popular believe you don't have to implement those interfaces to have LINQ support, you just need to have the methods they compile down to.

This is fine:

public class MyClass { 
  public MyClass Select<MyClass>(Func<MyClass, MyClass> func) { ... } 
}

var tmp = from m in new MyClass()
          select m;

Sure a .ToList() wont work though ;)

As you solving your problem try using the Cast<T>() extension method, that'll make it an IEnumerable<T> and allow you to LINQ to your hearts content.

Related Topic