2

I'm coding in c# on webpages/razor with MS SQL database

I have a table with the following columns

  • Sat1
  • Sat2
  • Sat3
  • Sat4
  • ...
  • Sat25

I want to loop through each of these, and assign the value to satAvail

I have the following

for (var i = 1; i < 26; i++)
{
    satWeek = "Sat" + i;
    satAvail = item.satWeek;
}

I want the equivalent of satAvail = item.Sat1; I've tried a few different lines but having no joy

2
  • This is not possible (in C#) Commented Jan 18, 2013 at 14:39
  • Don't use an ORM if you want to do this. Just use a traditional query method where the results are accessed through an indexer, making this trivial. Commented Jan 18, 2013 at 15:07

3 Answers 3

2

It's not clear if you're using an ORM or ADO, but assuming ADO, you could use something like:

DataTable dt = new DataTable();

        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn column in dt.Columns)
            {
                var satAvail = row[column];
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

1

use reflection

var value = item.GetType().GetProperty("Sat" + i).GetValue(item, null);

and if you want a sum (assuming Sat1... Sat2 are integers)

var sum = 0;
for (var i = 1; i < 26; i++) {
  sum +=(int)item.GetType().GetProperty("Sat" + i).GetValue(item, null);
}
satAvail = sum;

or linq way :

var sum = Enumerable.Range(1, 25)
                     .Select(x => (int)item.GetType().GetProperty("Sat" + x).GetValue(item, null))
                     .Sum();

2 Comments

Sat1 Sat2 are the column names and I'm getting Invalid column name "GetType".
@user1990727 you mean you have not a class corresponding to your table ? So my answer is far from usefull, indeed. How do you access your db ?
0

I'm not sure I'm clear on your actual requirement, but in general, when working with the Database helper, if you want to access a column value resulting from a Database.Query or Database.QuerySingle call, you can either do it using dot notation or an indexer.

For example, you may get data doing this:

var db = Database.Open("MyDatabase");
var item = db.QuerySingle("SELECT * FROM Mytable WHERE ID = 1");

If you know want to access the value of a column called Sat1, you would use item.Sat1. However, if the column name is represented as a variable, you would need to use an indexer instead:

var satWeek = "Sat" + "1";
var satAvail = item[satWeek];

1 Comment

sorry for not being clear earlier or knowing the exact terminologies - this works exactly as i wanted. brill thanks mike - you and your site has been a massive help to me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.