Converting a generic collection of a concrete type to a collection of a base type
I've got a number of classes that implement a specific interface (ISearchable) and I'd like to return an IEnumerable of the base type (ISearchable) from a static method, but I'm not sure how to convert it without making intermediate collections.
The code is pretty simple, one of the domain objects' implementations is like so:
public class account : ISearchable
{
public static 开发者_运维知识库IEnumerable<ISearchable> Search(string keyword)
{
// ORMVendorCollection<T> implements IQueryable<T>
ORMVendorCollection<account> results = /* linq query */
// this works if I change the return type to IEnumerable<account>
// but it uglifies client code a fair bit
return results.AsEnumerable<account>();
// this doesn't work, but it's what I'd like to achieve
return results.AsEnumerable<ISearchable>();
}
}
The client code, ideally looks like this:
public static IEnumerable<ISearchable> Search(string keyword)
{
return account.Search(keyword)
.Concat<ISearchable>(order.Search(keyword))
.Concat<ISearchable>(otherDomainClass.Search(keyword));
}
Use the Cast<T>
extension method
return results.Cast<ISearchable>();
For C# 4.0, you may be able to cast directly, since IEnumerable<>
is covariant
return (IEnumerable<ISearchable>)results.AsEnumerable();
Couldn't you just do something like?
public class account : ISearchable
{
public static IEnumerable<ISearchable> Search(string keyword)
{
var results = /* linq query */
foreach(var result in results)
yield return result;
}
}
精彩评论