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.
Additional information: Unable to cast object of type 'System.Collections.Generic.List`1[Row]' to type 'Table'.
How can I return an object of type Table out of an IEnumerable?
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;
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("")));
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With