Linq output as an interface?

Here is the code I'm trying to do:

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

The operator implements IOperator, but I get 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 do this to get what I need?

+4
source share
4 answers

Try the Cast<>() method:

 return c.Operators.Cast<IOperator>().ToList(); 
+6
source

If I changed 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 also works! Thanks for pushing in the right direction.

+4
source

Edit: Actually,

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

won't do the trick. Unfortunately

0
source

Use ConvertAll <>

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

for example: In this case, TEntity should be IBusinessUnit, but is a class, so I have the same problem with converting List<Operator> to List<IOperator> (assuming Operator implements IOperator).

In your case, as you said, the operator does not enter into an IOperator, but it does not matter - it will work anyway -

  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. } 
0
source

Source: https://habr.com/ru/post/1277173/


All Articles