c# - 如何将 List 转换为继承自 List<T> 的类型?

标签 c# linq casting

我有两个类:

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 的转换。

  1. (Table) 的转换抛出 InvalidCastException

Additional information: Unable to cast object of type 'System.Collections.Generic.List`1[Row]' to type 'Table'.

  1. 作为表的转换导致空对象

如何从 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/

相关文章:

java - 将什么传递给 Arrays 实例方法 toArray(T[] a) 方法?

C# 抽象类命名约定

c# - 此 C# 代码的含义是什么,我该如何使用它?

linq - 如何在Linq查询中使用Union

c# - Linq查询以计算数据表中的字段

c - 整数提升如何在 C Cast 上工作?

c++ - 如何不在 C++ 中将转换编译为枚举类型?

c# - 在 C# 中创建 session

c# - .NET 字符串中的货币符号放置

javascript - 函数的三元执行