user3953989
user3953989

Reputation: 1929

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.)

Upvotes: 3

Views: 1875

Answers (3)

Nawaraj
Nawaraj

Reputation: 1

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

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

Upvotes: -1

AJ X.
AJ X.

Reputation: 2770

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.

Upvotes: 1

Michael Liu
Michael Liu

Reputation: 55339

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.

Upvotes: 9

Related Questions