sukesh
sukesh

Reputation: 2423

find an object's property and get its value - C#

say there is a class like

class phones
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string Color {get; set;}
    public decimal Price {get; set;}
}
List<phones> myList = GetData();
//list is filled with objects

Now, I know the Id and the exact name of the object's property and want to get the value from the matching object.

private string GetValue(int pid, string featurename)
{
  string val = "";
 foreach(phones obj in myList)
  {
   if(obj.Id == pid)
    {
      //if featurename is 'Name', it should be
      //val = obj.Name;

      //if featurename is 'Price', it should return
      //val = obj.Price;
      break;
    }
  }
  return val;
}

Is this possible. Please advise.

Upvotes: 0

Views: 55

Answers (3)

Codeek
Codeek

Reputation: 1624

I think you want Property with given featurename and use it you could use lambda expression like this

or

Use PropertyInfo like this

foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
    string propertyName = p.Name;
    //....
}

Upvotes: 1

Piyush Parashar
Piyush Parashar

Reputation: 874

Use this:

 Phones phones= new Phones();          
 string returnValue = phones.GetType().GetProperty(featureName).GetValue(phones, null).ToString();

Also, remember to add validation for input featureName and error handling.

Upvotes: 1

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

How about this:

 foreach(phones obj in myList)
  {
   if(obj.Id == pid)
    {
      if (featurename == "Name")
      {
         return obj.Name;
      }
      else if (featurename == "Price")
      {
         return obj.Price.ToString();
      }
      else
      {
         return string.Empty;
      }
    }
  }

Upvotes: 1

Related Questions