Solved

For Loop to populate class with same property names

Posted on 2014-04-11
8
251 Views
Last Modified: 2014-04-17
I have 2 classes with properties mostly of the same name. I have a List<Type1> and need to use a for loop to populate a List<Type2>. There are 50+ properties to set so to avoid having a lot of code to say:

foreach (var b in List1)
{
var c = new Type2
c.P1=b.P1
c.P2=b.P2
etc..
}

Is there a way to set properties where the property name is the same?

There a re a couple of additional properties in Type2 but I can set these manually.
0
Comment
Question by:wint100
  • 3
  • 3
  • 2
8 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 39993552
You'll probably have to resort to reflection. Something along the lines of:
        static void Main(string[] args)
        {
            List<Type1> list1 = new List<Type1>() { new Type1 { FirstName = "Bob", LastName = "Smith" }, new Type1 { FirstName = "Jane", LastName = "Doe" } };
            List<Type2> list2 = new List<Type2>();

            foreach (Type1 t1 in list1)
            {
                Type2 t2 = new Type2();
                CloneProperties<Type1, Type2>(t1, t2);

                list2.Add(t2);
            }

            Console.ReadLine();
        }

        public static void CloneProperties<T, S>(T source, S target)
        {
            PropertyInfo[] sourceProp = source.GetType().GetProperties();
            PropertyInfo[] targetProp = target.GetType().GetProperties();

            foreach (PropertyInfo p in sourceProp)
            {
                PropertyInfo temp = targetProp.Where(x => x.Name == p.Name).First();
                if (temp != null)
                {
                    target.GetType().InvokeMember(p.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, null, target, new object[] { p.GetValue(source) });
                }
            }
        }

Open in new window

0
 
LVL 1

Author Comment

by:wint100
ID: 39993805
This looks ideal. I do get one complier error though for the p.GetValue(source), it seems to need more args:

Error      351      No overload for method 'GetValue' takes 1 arguments
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39993817
Which version of .Net are you targeting?
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 1

Author Comment

by:wint100
ID: 39993818
Currently 4.0
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39993821
Ah, in that case you'll need to change it to:
p.GetValue(source, null)

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39994176
Why not create a "copy" constructor that you can simply pass an existing instance to?

e.g.

public class Type2
{
    public Type2(Type1 original)
    {
        this.P1 = original.P1;
        this.P2 = original.P2;
        etc...
    }
}

Open in new window


True, you still have to flesh out all of the property assignments, but you're doing so only in one place. Now whenever you require a duplication you simply construct a new object:

e.g.

foreach (var b in List1)
{
    var c = new Type2(b);
}

Open in new window


Reflection is an expensive operation that is generally best used when you don't have another alternative.
0
 
LVL 1

Author Comment

by:wint100
ID: 39994189
Interesting, I have implemented Carl's emthod and is done seem to work. I'm trying to avoid typing out 120 properties and having to remember to change the code when I change the class.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39994195
There's nothing truly evil about Reflection...it's just expensive since it's not done at compile time. If it solves your need, then all should be good. But if you start noticing adverse performance issues, the Reflection bit should be kept in mind as a source of the problem.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question