Alex Rivera | Logout

How do I cast a List<T> effectively?

Asked 2009-02-02T20:24:02.950
30

I have a

List<InputField> 

but I need a

List<IDataField>  

Is there a way to cast this in c#? Or use Linq to get same result?

I have two classes that implement the same interface:

interface IDataField { }
class InputField : IDataField { }
class PurchaseField : IDataField { }

This List comes from a Linq-to-Sql query:

List<InputField> list = (from i .... select i).ToList();
Edit
Report

2 Answers

9

You could also use List.ConvertAll.

Documentation: http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx

Example:

List<IDataField> newList = oldList.ConvertAll(i => i as IDataField);
answered 2009-02-02T20:39:36.117
1

I don't know that a direct cast would have the desired effect. The rare few times I've done this, it's usually something like:

List<InputField> list = .....
List<IDataField> list2 = new (List<IDataField>((IDataField[])list.ToArray()));
answered 2009-02-02T20:25:59.670

Your Answer