Solved

For Loop to populate class with same property names

Posted on 2014-04-11
8
249 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
 
LVL 1

Author Comment

by:wint100
ID: 39993818
Currently 4.0
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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 74

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 74

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
crm development 2 37
Help with error message for ReportViewer in VS2015 4 24
Long URL in SMS 6 24
bulid json format 3 19
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

705 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now