0

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; }
}
Muhammad Sulaiman
  • 2,399
  • 4
  • 14
  • 28
Trey Balut
  • 1,355
  • 3
  • 19
  • 39
  • 2
    Can you describe why you are trying to do this? It's unclear what problem you are trying to solve, but there's a good chance there's a better way to solve the problem than this. It's a typical [XY problem](https://xyproblem.info/). – Xerillio Oct 08 '22 at 17:12
  • Does this answer your question? [LINQ select property by name](https://stackoverflow.com/questions/47781469/linq-select-property-by-name) – BurnsBA Oct 08 '22 at 17:23
  • I want to do this because I the array is apprx Length 20. And alternative is to use a switch statement. – Trey Balut Oct 08 '22 at 18:38
  • Can you make the salary properties an array or Dictionary? – Klaus Gütter Oct 08 '22 at 20:06
  • Klaus, they are already in a string array. How would a Dictionary work in this situation. – Trey Balut Oct 09 '22 at 14:13

1 Answers1

1

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) };
Muhammad Sulaiman
  • 2,399
  • 4
  • 14
  • 28