views:

44

answers:

3

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));
}
+7  A: 

Use the Cast<T> extension method

return results.Cast<ISearchable>();
JaredPar
Thank you Jared. edit: *waits 10 mins*
SnOrfus
+1  A: 

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)
            yeild return result;
    } 
} 
asawyer
+2  A: 

For C# 4.0, you may be able to cast directly, since IEnumerable<> is covariant

return (IEnumerable<ISearchable>)results.AsEnumerable();
Mark H
+1 but alas, I'm restricted to .NET 3.5 for the moment.
SnOrfus
Variance works in the 3.5 framework, just unfortunate that you can't have the language features. (But I'm pretty sure you can build a class library that uses variance, and utilise it from a 3.5 application)
Mark H