tags:

views:

15

answers:

1

Hi,

I have a linq2sql class with fields WeekEnding1 WeekEnding2 WeekEnding3 WeekEnding4

I want to write some c# using the fields in a for loop.

Take this for example:

for(int i=1; i<=4; i++)
{
   Msgbox(myClass.WeekEnding + i)
}

I realise that wont work but what will??

Malcolm

A: 

Unless you want to get into something with reflection, this will:

MsgBox(myClass.WeekEnding1);
MsgBox(myClass.WeekEnding2);
MsgBox(myClass.WeekEnding3);
MsgBox(myClass.WeekEnding4);

You can do what you're trying to do with reflection by putting this inside the loop:

PropertyInfo info myClass.GetType()
    .GetProperty("WeekEnding" + i.ToString(),
        BindingFlags.Public | BindingFlags.Instance);
MsgBox(info.GetValue(myClass, null));

But I'd recommend the first approach! The second approach will have to find the property in question on each pass through the loop, adding a considerable overhead.

In any event, your underlying data model sounds very much like it might need normalising - this is a common bad smell!

David M