0

I have following object structure where B is derived from A and I am getting input as List<A> with lots of records. I want to convert thatList<A> to List<B> with easy steps (without looping). What is the best way to achieve the same.

Note: I don't want to use AutoMapper.

    public class A
    {
        public A() { }
        public virtual string Name
        {
            get;
            set;
        }
    }

    public class B : A
    {
        public B()
            : base()
        {
        }
        private string _name;
        public override string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = string.Concat("Hello ", base.Name);
            }
        }

        public string Id
        {
            get { return "101"; }
        }
    }
leppie
  • 115,091
  • 17
  • 196
  • 297
Sumit Deshpande
  • 2,155
  • 2
  • 20
  • 36

2 Answers2

2

You can do this by declaring constructor for class B from class A in this way:

public B(A a):base()
{
    this._name = a.Name;
}

And than do this:

var listA = new List<A> { new A { Name = "John" }, new A { Name = "Peter" }, new A { Name = "Julia" } }; 
List<B> listB = listA.Select(x=> new B(x)).ToList(); 
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
0

Based on the comments this is the output, though I still don't really understand the point.

        List<A> thisIsA = new List<A>();

        thisIsA.Add(new B());

        List<B> thisIsB = new List<B>();
        thisIsB.AddRange(thisIsA.Cast<B>());
russelrillema
  • 452
  • 7
  • 14