Home > other >  How do I substitute a string for a property name in an ObservableCollection
How do I substitute a string for a property name in an ObservableCollection

Time:10-09

I want to use a string from an Array that represents a property name in an ObservableCollection.

How do I correctly format the string so that I can use it as a property in a foreach loop of an Observable Collection without getting a error?

System.FormatException: 'Input string was not in a correct format.'

Here is my code:

string[] salaryArray = { "Salary1", "Salary2" };

var employees = new ObservableCollection<Employee>();
employees.Add(new Employee() { Name = "Ali", Title = "Developer", Salary1 = 25, Salary2 = 26 });
employees.Add(new Employee() { Name = "Ahmed", Title = "Programmer", Salary1 = 28, Salary2 = 29.5 });
employees.Add(new Employee() { Name = "Amjad", Title = "Desiner", Salary1 = 30, Salary2 = 32.4 });

foreach (Employee emp in employees)
{
    Console.WriteLine(emp.Name   " "   emp.Salary2.ToString());
}

foreach (string s in salaryArray)
{
    string tempStr = "emp.s";

    foreach (Employee emp in employees)
    {
        // Attempt to use a string from the array Input error at this line
        Console.WriteLine(emp.Name   " "   Convert.ToDouble(tempStr));
    }
}

Here is my Employee class:

public class Employee
{
    public string Name { get; set; }
    public string Title { get; set; }
    public double Salary1 { get; set; }
    public double Salary2 { get; set; }
}

CodePudding user response:

It seems like you want to read/print the salaries of the employees based on the order of the properties' names in salaryArray list.

You have to use reflection

foreach (string tempStr in salaryArray)
{
    foreach (Employee emp in employees)
    {
        Console.WriteLine(emp.Name   " "   typeof(Employee).GetProperty(tempStr)?.GetValue(emp)));
    }
}

And better to define salaryArray like this

string[] salaryArray = { nameof(Employee.Salary1), nameof(Employee.Salary2) };
  • Related