Cast/Convert IEnumerable to IEnumerable?

前端 未结 6 2085
我在风中等你
我在风中等你 2021-01-04 08:48

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 wo

6条回答
  •  醉话见心
    2021-01-04 09:24

    Use Select instead of Cast in order to indicate how to perform the conversion from one type to another:

    IEnumerable p = pwa.Select(x => new Person { Id = x.Id, Name = x.Name });
    

    Also as PersonWithAge will always contain the same properties as Person plus a couple more it would be better to have it inherit from Person.

提交回复
热议问题