简体   繁体   中英

How to convert List<object> to IEnumerable<T>

How do I return expected as IEnumerable<T> given the code below?

public List<object> expected = new List<object>();

public IEnumerable<T> SqlQuery<T>(string sql)
{
    // Return expected as IEnumerable<T>
}

(This is a class that was created for unit tests to mock the Entity Framework SqlQuery<T> method. We can set our expected result ahead of time and simply have it return what you would expect.)

Assuming that expected really contains instances of type T , you can use the LINQ Cast operator:

public IEnumerable<T> SqlQuery<T>(string sql)
{
    return expected.Cast<T>();
}

InvalidCastException will be thrown if the cast fails for any element.

In case you have a list that contains many sub types and you only want to return a specific sub type, you can also do:

public IEnumerable<T> SqlQuery<T>(string sql)
{
    return expected.OfType<T>();
}

In this case, say you have a Person class that is a base class for Cops and Robbers .

If you'd like all "people" from your collection, you can write: OfType<Person>

But if you only wanted the robbers from the collection, use OfType<Robbers>

If you ask for a type that doesn't exist in the expected collection like OfType<Footballer> , an empty collection will be returned.

Its better to use LINQ Cast operator to convert to desired IEnumerable.

public IEnumerable<T> SqlQuery<T>(string sql)
{
return expected.Cast<T>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM