S
S
Smilley2016-09-22 16:23:53
Programming
Smilley, 2016-09-22 16:23:53

How to make a list of an inherited class from a base class list?

Good afternoon. stumbled on the following problem:
There is a main class:

public class A 
{
public string a { get; set; }
//Всего около 100 свойств
}
There is an inherited class:
public class B : A
{
public string b { get; set; }
//Всего около 10 дополнительных свойств
}

There is a code that creates List<A>, now there is a need List<A>to create from List<B>, however, none of the examples found leads to the desired result:
List<A> listA = getListA();
List<B> listB = listA.OfType<B>().ToList();
// Не ругается, но список пустой
List<A> listA = getListA();
List<B> listB = listA.Cast<B>().ToList();
// Выдаёт Exception: Ivalid Cast

I would be grateful for advice. Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
Fat Lorrie, 2016-09-22
@Free_ze

* Something wrong with the design .*
You can't directly downcastA objects into objects B, because A is not B . Because it Bcontains some additional state ( b), which is not in Aand the compiler does not know what it should be in its current form (it was Aconstructed differently than Band how to get a valid Bfrom A- only the programmer knows). The runtime ( )
is trying to tell you about this . As for methods that don't result in what you want: - filters by type and legitimately returns an empty list (you have a list , there really isn't )Invalid Cast
Enumerable.Cast<T>()- consistently makes casts, which is impossible.
We can try to copy the objects into a new list:
But this will work only if we can get the Anecessary data from to construct the object B. It is important to understand that these will be OTHER objects. If A is inherently non-copyable, then this trick will fail.

M
Maxim Grekhov, 2016-09-22
@Sterk

Create a constructor in class B that takes class A and initializes its fields with values ​​from A. Then
var listB = listA.Select(a=>new B(a)).ToList();

A
AxisPod, 2016-09-23
@AxisPod

There is a clear problem with the architecture. For good in this case, you need to work with interfaces whenever possible and use covariance / contravariance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question