-1

I have an object, which inside is another object that is a list of an object.

What I am trying to do is iterate through the list and to take each a value from the list to set a label. So, if I have 5 values in my list:

for (x=0; list.count; x++)
{
  lblDayOne.Text = list[x].DayOne.Value; <-I want to set this with the value relevant for Day One and so on and so forth for each label as below
  lblDayTwo.Text = list[x].DayTwo.Value;
  lblDayThree.Text = list[x].DayThree.Value;
  lblDayFour.Text = list[x].DayFour.Value;
  lblDayFive.Text = list[x].DayFive.Value;
}

Is there a way to do this? I tried with foreach but no luck. This is all C#

Andy5
  • 2,319
  • 11
  • 45
  • 91

1 Answers1

3

Call List<T>.ForEach(). Pass it a lambda.

Enumerable.Range(0,9).ToList().ForEach( n => Console.WriteLine(n) );

UPDATE

Wait a minute, are you trying to iterate not over your list of objects, but over a list of PROPERTIES in each object in the list (DayOne, DayTwo, etc.), and possibly also automagically link them up with variables with similar names? No, there's nothing like that in C#. You'd have to roll your own using reflection, and that would be a lot of work for very little payoff.

You could consider storing those values not as properties, but in a Dictionary<String,String>, or perhaps an array String DayValues[]; either of those would support iteration, but you'd still have the problem of linking up the items programmatically with the label controls. You might be able to look up the controls by name, though, depending how you're doing your UI -- ASP.NET has FindControl(string id), for example.

But what you have above is a perfectly clear, readable way of doing it, just the way it is. That's how I'd do it in production code, except that I'd assign list[x] to a local variable at the top of the loop block to clear up the visual noise a bit. An iterating lambda solution would sacrifice clarity for cleverness, not a good tradeoff in code you'll have to maintain. If it's just fun code, on the other hand, by all means stretch out and learn something new. Lambdas are a fantastic toy.

If that's really the question you're asking, you should edit your question for clarity.

Community
  • 1
  • 1