I am using C# to create an app and want to be able to easily do a foreach() loop through my 120 strings that i have. All these strings are constructed as below:
public class _currentweekapi
{
public string _1_artist { get; set; }
public string _2_artist { get; set; }
public string _3_artist { get; set; }
...
}
Is it possible to be able to do a foreach() loop to loop through all the values. The strings are set automatically from a JSON feed so i cannot get the values straight into a list.
I have read up on the topic and understand there are ways through ‘Reflection’ but I am new to C# and reading up on it doesn’t make any sense to me.
Could someone please help me with a solution to this stating exactly how I could implement this?
The first thing you should be trying to do, is NOT store the strings in explicitly named properties, as your class definition appears to be doing. The most appropriate scenario would seem to be a List<string> type property that can hold them all in your class. This would also mean you already have your list ready to go.
So, if you are able to, change the class, or use another, which accepts the JSON feed, and uses .Add() on a property of type List<string>, rather than explicitly setting 120 properties.
Like this:
Then, you have your list in the property Artists, and can use the list directly, or return it by doing:
However, you seem to have indicated that you cannot change the fact that they end up served to you as individual properties in the class you showed us, so…
Assuming you have no choice, but to start from a class such as the one you showed, here is a way you could do a loop through all those values, just as you asked for, all that will be required is that you pass your class instance into one of the methods below as the one parameter that each requires:
Either one should help, but do not use the dictionary one, as it entails more overhead, unless you really need to know the name of the property each artist came from as well, in which case it is more helpful than a simple list.
Incidentally, since the methods are generic, that is, they accept a parameter of type T, the same methods will work for ANY class instance, not just the one you are struggling with now.
REMEMBER: although it may appear extremely convenient to you at the moment, this is not necessarily the best way to approach this. Better than this, would be the initial suggestions I made for re-working the class altogether so this sort of thing is not required.