C# casting question: from IEnumerable to custom type

Posted by Sarah Vessels on Stack Overflow See other posts from Stack Overflow or by Sarah Vessels
Published on 2010-05-25T13:22:02Z Indexed on 2010/05/25 13:31 UTC
Read the original article Hit count: 168

Filed under:
|
|
|
|

I have a custom class called Rows that implements IEnumerable<Row>. I often use LINQ queries on Rows instances:

Rows rows = new Rows { row1, row2, row3 };
IEnumerable<Row> particularRows = rows.Where<Row>(row => condition);

What I would like is to be able to do the following:

Rows rows = new Rows { row1, row2, row3 };
Rows particularRows = (Rows)rows.Where<Row>(row => condition);

However, I get a "System.InvalidCastException: Unable to cast object of type 'WhereEnumerableIterator1[NS.Row]' to type 'NS.Rows'". I do have a Rows constructor taking IEnumerable<Row>, so I could do:

Rows rows = new Rows { row1, row2, row3 };
Rows particularRows = new Rows(rows.Where<Row>(row => condition));

This seems bulky, however, and I would love to be able to cast an IEnumerable<Row> to be a Rows since Rows implements IEnumerable<Row>. Any ideas?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ