In C # there is a way to call an object property with a variable, something like this:
string fieldName = "FirstName";
Console.WriteLine(customer.&fieldName);
Answer:
Great, thanks for the quick answers, here is what I tried to do:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace TestLinqFieldIndex
{
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { ID = 1, FirstName = "Jim", LastName = "Smith" });
customers.Add(new Customer { ID = 2, FirstName = "Joe", LastName = "Douglas" });
customers.Add(new Customer { ID = 3, FirstName = "Jane", LastName = "Anders" });
var customer = (from c in customers
where c.ID == 2
select c).SingleOrDefault();
string[] fieldNames = { "FirstName", "LastName" };
foreach (string fieldName in fieldNames)
{
Console.WriteLine("The value of {0} is {1}.", fieldName, customer.GetPropertyValue(fieldName));
}
Console.ReadLine();
}
}
public class Customer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetPropertyValue(string fieldName)
{
PropertyInfo prop = typeof(Customer).GetProperty(fieldName);
return prop.GetValue(this, null).ToString();
}
}
}
source
share