Solved

For Loop to populate class with same property names

Posted on 2014-04-11
8
254 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

726 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