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
Solved

For Loop to populate class with same property names

Posted on 2014-04-11
8
252 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
DevOps Toolchain Recommendations

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

 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

809 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