?
Solved

For Loop to populate class with same property names

Posted on 2014-04-11
8
Medium Priority
?
255 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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

770 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