Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq output as an Interface?

Here's the code that I'm attempting to do:

public IList<IOperator> GetAll()
{
      using (var c = new MyDataContext())
      {
          return c.Operators.ToList();
      }
}

Operator implements IOperator, but I'm getting the following compilation error:

Cannot implicitly convert type 'System.Collections.Generic.List<MyProject.Core.Operator>' to 'System.Collections.Generic.IList<MyProject.Core.Model.IOperator>'. An explicit conversion exists (are you missing a cast?)

How do I cast this to get what I need?

like image 898
kenstone Avatar asked Dec 30 '22 10:12

kenstone


2 Answers

Try the Cast<>() method:

return c.Operators.Cast<IOperator>().ToList();
like image 181
Panos Avatar answered Jan 11 '23 16:01

Panos


If I change the code to the following:

public IList<IOperator> GetAll()
{
      using (var c = new MyDataContext())
      {
           var operators = (from o in c.Operators
                            select o).Cast<IOperator>();

           return operators.ToList();
      }
}

it not only compiles but actually works! Thanks for the nudges in the right direction.

like image 24
kenstone Avatar answered Jan 11 '23 17:01

kenstone