Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

Iam having a class with 100 properties and another mapping class with 20 properties which will match with in 100 properties. Now when I map with mapping object I should get 100 properties with values of 20 properties which were matched, remaining 80 properties should get null though its having value. How to achieve this can you guys help me on this.

Please let me know if I am not clear.

Ex:
1)
new class {
               Property1 = value,
               property2=value,
               property3= value
             }

2) Mapping class:
new class {
             Property1,
               property2
}


Output should be:
{
      Property1 = value,
      property2=value,
      property3= null
}


What I have tried:

I am not having any best solution. My thought was looping the properties and make null non matching properties. Please suggest me the best solution for this.
Posted
Updated 12-Dec-16 12:56pm
Comments
F-ES Sitecore 9-Dec-16 4:52am    
You haven't shown your code so how can we tell you what the problem is?
NaVeN Kumar 9-Dec-16 4:54am    
I am not sure whether my thought is best solution or not. I will try it and post.
CPallini 9-Dec-16 5:22am    
I see no alternative to looping.
Nathan Minier 9-Dec-16 10:42am    
Constructor injection would work.

public MyClassWith100Props(MyMappingClass map){ ... //assign }

1 solution

Hi NaVeN,

Your idea of looping through properties should work. You need to add the reflection namespace:
C#
using System.Reflection;
Then you need to access the properties of the 100-value class, and the matching class. For this you store all of them in PropertyInfo[] array:
C#
PropertyInfo[] PropertiesOf100Class = typeof(ClassHaving100Properties).GetProperties();
PropertyInfo[] PropertiesOfMappingClass = typeof(MappingClass).GetProperties();
Then you browse through each property of the matching class and see if there is a match in the primary class (i.e. the class having 100 values).
C#
foreach (var MatchingProperty in PropertiesOfMappingClass)
    foreach (var Property in PropertiesOf100Class)                
        if (MatchingProperty.Name.Equals(Property.Name))
            MessageBox.Show(Property.Name); // Replace this line with whatever you want to do.
Please change the classnames accordingly.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900