【问题标题】:How can I cast a List into a type which inherits from List<T>?如何将 List 转换为从 List<T> 继承的类型?
【发布时间】:2019-02-17 21:42:37
【问题描述】:

我有两个班级:

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

附加信息:无法将“System.Collections.Generic.List`1[Row]”类型的对象转换为“Table”类型。

  1. 使用 as Table 进行转换会导致 null 对象

如何从 IEnumerable 中返回 Table 类型的对象?

【问题讨论】:

标签: c# linq casting


【解决方案1】:

你可以做一个扩展方法来完成这项工作:

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;

【讨论】:

  • @D.Weder 欢迎您。但是您在Table 中还有其他属性吗?因为在这个解决方案中他们将获得默认值!
【解决方案2】:

我假设您的 tableObjectList&lt;Row&gt;。每个Table 都是List&lt;Row&gt;,但不是每个List&lt;Row&gt; 都是Table,这就是强制转换不起作用的原因。

听起来提供构造函数是一个显而易见的解决方案:

public class Table : List<Row>
{
    public Table(IEnumerable<Row> rows) : base(rows) {}
}

table = new Table(tableObject.Where(x => x.Value.Equals("")));

【讨论】:

    【解决方案3】:

    你应该这样做:

    public class Row{
        //whatever you have inside it
        public string MyValue{get;set;}
    }
    
    public class Table{
        public List<Row> Rows{get;set;}
    }
    
    Table table = new Table();
    //renaming tableObject to bigListOfRows
    table.Rows = bigListOfRows.Where(x => x.MyValue.Equals("")).ToList();
    

    【讨论】:

      【解决方案4】:
      Table table = new Table();
      

      不是列表,所以你应该这样做:

      var tables = new List<Table>();
      var tableObject = new List<Table>{};
      tables = tableObject.ToList();
      

      【讨论】:

      • 您在 List 上调用 ToList() 并将其分配给另一个列表...它可能更短,例如 tables = tableObject。但我认为他的问题有别的意思。
      猜你喜欢
      • 2017-03-11
      • 2013-08-03
      • 1970-01-01
      • 2011-07-19
      • 2012-11-15
      • 2022-11-02
      • 2019-10-03
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多