views:

580

answers:

4

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?

+4  A: 

Try the Cast<>() method:

return c.Operators.Cast<IOperator>().ToList();
Panos
A: 

Edit: Actually,

return (List< IOperator >)c.Operators.ToList();

would not do the trick. Sorry

Grank
No, this doesn't work.
Panos
List<Operator> does not implement List<IOperator>, so you can't up-cast in this way.
David B
oh, yeah, good point
Grank
+4  A: 

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.

kenstone
A: 

Use ConvertAll<>

http://msdn.microsoft.com/en-us/library/kt456a2y.aspx

e.g.: In this case, TEntity must be an IBusinessUnit, but is a class, so i have the same trouble of converting List<Operator> to List<IOperator> (assuming Operator implements IOperator).

In your case, like you said, Operator doesn't impelement IOperator, but that doesn't matter - this will still work -

 public static IList<IBusinessUnit> toIBusinessUnitIList(List<TEntity> items)
      {

      return items.ConvertAll<IBusinessUnit>(new Converter<TEntity, IBusinessUnit>(TEntityToIBuisinessUnit));
      }

  /// <summary>
  /// Callback for List<>.ConvertAll() used above.
  /// </summary>
  /// <param name="md"></param>
  /// <returns></returns>
  private static IBusinessUnit TEntityToIBuisinessUnit(TEntity te)
  {
   return te;  // In your case, do whatever magic you need to do to convert an Operator to an IOperator here.
  }
Frank Tzanabetis