shamim
shamim

Reputation: 6770

How to Copy Common properties List<x> to List<y>

how to copy list to another list

class x and class y both have several common properties want to copy common properties to another list ,suppose x to y

Have two list one to copy one list content to another, I use bellow syntax to copy list to list items.

List<SomeType2> list1 = new List<SomeType2>();
List<SomeType> list2 = new List<SomeType>();

// This will copy all the items from list 1 to list 2
list1.ForEach(i => list2.Add(i));

But My list1 not like same as list2 ,when they have same type of above syntax work perfectly.

My list are not same so I need to use bellow syntax for copy

List<Y> y = new List<Y>(x.ConvertAll<Y>(e => { return new Y { Id = e.Id, Name = e.Name }; }));

But I don’t want to use static “Id = e.Id, Name = e.Name” ,Need to use this process several time on several list(whose properties are different) so it’s better to me write any common thing which can do that for me.

If have any query please ask,Thanks in advanced.Any type of suggestion will be acceptable

Upvotes: 1

Views: 880

Answers (5)

I4V
I4V

Reputation: 35353

You can use reflection

static T2 Copy<T1, T2>(T1 from)
{
    T2 to = Activator.CreateInstance<T2>();
    Type toType = typeof(T2);

    foreach (var p in from.GetType().GetProperties())
    {
        var prop = toType.GetProperty(p.Name);
        if (prop != null)
            prop.SetValue(to, p.GetValue(from,null),null);
    }

    return to;
}

SomeType2 t2 = Copy<SomeType1,SomeType2>(new SomeType1(){/*....*/});

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

If you want to map properties with same names, then you can use something like Automapper (available from NuGet), which will do it automatically for you. Add mapping somewhere on application start:

Mapper.CreateMap<Source, Destination>();

Default mapping will provide mapping for properties with same names. So, then simply map lists:

List<Source> list1 = new List<Source>();
List<Destination> list2 = Mapper.Map<List<Destination>>(list1);

Upvotes: 1

David S.
David S.

Reputation: 6105

If you have common properties, perhaps they should be in an interface, or a base class.

Upvotes: 0

Mortalus
Mortalus

Reputation: 10712

Just use .select

List<y> = oldList.select(x=> new y{prop1 = x.prop1}).ToList();

Upvotes: 0

Bas
Bas

Reputation: 27085

Consider using AutoMapper, it was conceived to do exactly this.

Upvotes: 1

Related Questions