Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast a List into a type which inherits from List<T>?

Tags:

c#

casting

linq

I have two classes:

public class Row : Dictionary<string,string> {}
public class Table : List<Row> {}

In a method which should returns an object of type Table, I try to filter an object of type Table with the Where-Statement and return this object after filtering.

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

My problem is the cast of the resulting IEnumerable.

  1. Conversion with (Table) throws an InvalidCastException

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

  1. Conversion with as Table results in an null object

How can I return an object of type Table out of an IEnumerable?

like image 297
D.Weder Avatar asked Sep 13 '18 07:09

D.Weder


3 Answers

You can make an extension method to do this job:

static class Extensions
{
    public static Table ToTable<T>(this IEnumerable<T> collection) where T: Row
    {
        Table table = new Table();
        table.AddRange(collection);
        return table;
    }
}

Now you can simply call this method:

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

Or you can do it directly, since you create an empty Table:

Table table = new Table();
table.AddRange(tableObject.Where(x => x.Value.Equals("")));
return table;
like image 95
Mong Zhu Avatar answered Oct 01 '22 20:10

Mong Zhu


I assume your tableObject is a List<Row>. Every Table is a List<Row> but not every List<Row> is a Table, that's why casting doesn't work.

It sounds like providing a constructor would be an obvious solution:

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

table = new Table(tableObject.Where(x => x.Value.Equals("")));
like image 40
Tim Schmelter Avatar answered Oct 01 '22 20:10

Tim Schmelter


You should do something like this:

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();
like image 32
maximelian1986 Avatar answered Oct 01 '22 21:10

maximelian1986