Reputation: 2184
I have the following query:
var result = context.BEntries
.Where(x => x.a == "a")
.Select(x => new MyClass()
{
a = x.a
}).ToList();
I get a result of type List<MyClass>
. However, I must return IEnumerable<IMyclass>
. How do I cast this to its generic definition?
Upvotes: 3
Views: 1432
Reputation: 54887
If you're using an older version of C# that does not support covariance, you can use Cast
:
var result = context.BEntries
.Where(x => x.a == "a")
.Select(x => new MyClass() { a = x.a })
.AsEnumerable()
.Cast<IMyClass>();
Upvotes: 3
Reputation: 887451
You don't need to.
IEnumerable<T>
is covariant; List<MyClass>
is implicitly convertible to IEnumerable<IMyClass>
.
.Net 3.5 does not use covariance, so you'll need to cast it yourself.
You can either call .Cast<IMyClass>()
or cast the select
expression to IMyClass
so that the query returns IMyClass
in the first place.
Upvotes: 7
Reputation: 466
Do not use var
, simple define a List
or IEnumerable
of your interface
Upvotes: 0
Reputation: 2931
As long as MyClass implements IMyClass this should be fine as it is.
Upvotes: 0