[英]How to convert List<object> to IEnumerable<T>
How do I return expected
as IEnumerable<T>
given the code below? 如果给出下面的代码,我如何返回
expected
IEnumerable<T>
?
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.) (这是为单元测试创建的类,用于模拟Entity Framework
SqlQuery<T>
方法。我们可以提前设置我们的预期结果,并让它返回您期望的结果。)
Assuming that expected
really contains instances of type T
, you can use the LINQ Cast operator: 假设
expected
实际上包含类型T
实例,您可以使用LINQ Cast运算符:
public IEnumerable<T> SqlQuery<T>(string sql)
{
return expected.Cast<T>();
}
InvalidCastException will be thrown if the cast fails for any element. 如果任何元素的强制转换失败,将抛出InvalidCastException。
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
. 在这种情况下,假设您有一个
Person
类,它是Cops
和Robbers
的基类。
If you'd like all "people" from your collection, you can write: OfType<Person>
如果你喜欢你的收藏中的所有“人”,你可以写:
OfType<Person>
But if you only wanted the robbers from the collection, use OfType<Robbers>
但是,如果您只想要收藏中的劫匪,请使用
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. 如果您要求在
OfType<Footballer>
等expected
集合中不存在的类型,则将返回空集合。
Its better to use LINQ Cast operator to convert to desired IEnumerable. 最好使用LINQ Cast运算符转换为所需的IEnumerable。
public IEnumerable<T> SqlQuery<T>(string sql)
{
return expected.Cast<T>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.