我有两个类:
public class Row : Dictionary<string,string> {}
public class Table : List<Row> {}
在一个应该返回类型为Table的对象的方法中,我尝试使用Where-Statement过滤类型为Table的对象过滤后返回该对象。
Table table = new Table();
table = tableObject.Where(x => x.Value.Equals("")).ToList();
return table;
我的问题是生成的 IEnumerable 的转换。
- 与(Table) 的转换抛出 InvalidCastException
Additional information: Unable to cast object of type 'System.Collections.Generic.List`1[Row]' to type 'Table'.
- 与作为表的转换导致空对象
如何从 IEnumerable 返回类型为 Table 的对象?
最佳答案
您可以创建一个扩展方法来完成这项工作:
static class Extensions
{
public static Table ToTable<T>(this IEnumerable<T> collection) where T: Row
{
Table table = new Table();
table.AddRange(collection);
return table;
}
}
现在你可以简单地调用这个方法:
table = tableObject.Where(x => x.Value.Equals("")).ToTable();
或者您可以直接执行此操作,因为您创建了一个空的 Table
:
Table table = new Table();
table.AddRange(tableObject.Where(x => x.Value.Equals("")));
return table;
关于c# - 如何将 List 转换为继承自 List<T> 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52308892/