I am having a list of Person as follows:
- var obj = new List<Person> { new Person { ID = 1, Name = "Arunava" }, new Person { ID = 2, Name ="Bubu" } };
My goal is to get the output as : Name=Arunava ID=1
Name=Bubu ID=2
in the console. Let's see how we can achieve that without using reflection. I used Linq.Expressions to achieve this.
Simple method to add in your model class, called GetPropertyName and also change the ToString method. My model class is as follows:
- public class Person
- {
- public string Name { get; set; }
- public int ID { get; set; }
- public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
- {
- var me = propertyLambda.Body as MemberExpression;
- return me.Member.Name;
- }
- public override string ToString()
- {
- return String.Format("{0}={1} {2}={3}", GetPropertyName(() => Name), Name,GetPropertyName(()=>ID),ID);
- }
- }
We are ready to get the expected result. See my console app:
- var obj = new List<Person> { new Person { ID = 1, Name = "Arunava" }, new Person { ID = 2, Name ="Bubu" } };
- obj.ForEach(data=> Console.WriteLine(data));
Try this now. Hope this helps.