Alex Rivera | Logout

Cast/Convert IEnumerable<T> to IEnumerable<U>?

Asked 2009-11-21T16:45:16.470
15

The following complies but at run time throws an exception. What I am trying to do is to cast a class PersonWithAge to a class of Person. How do I do this and what is the work around?

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class PersonWithAge
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<PersonWithAge> pwa = new List<PersonWithAge>
        {
            new PersonWithAge {Id = 1, Name = "name1", Age = 23},
            new PersonWithAge {Id = 2, Name = "name2", Age = 32}
        };

        IEnumerable<Person> p = pwa.Cast<Person>();

        foreach (var i in p)
        {
            Console.WriteLine(i.Name);
        }
    }
}

EDIT: By the way PersonWithAge will always contain the same properties as Person plus a couple more.

EDIT 2 Sorry guys but I should have made this a bit clearer, say I have two db views in a database that contains the same columns but view 2 contains 1 extra field. My model view entities are generated by a tool that mimics the database views. I have a MVC partial view that inherits from one of the class entities but I have more than one way to grab data...

Not sure if this helps but it means that I cant make personWithAge inherit from person.

Edit
Report

1 Answer

21

You can't cast because they are different types. You have two choices:

1) Change the class so that PersonWithAge inherits from person.

class PersonWithAge : Person
{
        public int Age { get; set; }
}

2) Create new objects:

IEnumerable<Person> p = pwa.Select(p => new Person { Id = p.Id, Name = p.Name });
answered 2009-11-21T16:48:39.007

Your Answer