2

I'm trying to get all records from a table and loop through it.

Pseudo Code:

database.dbDataContext db = new database.dbDataContext();

protected void Page_Load(object sender, EventArgs e)
{

    List<database.User> data = db.Users.ToList();

    // rows
    for (int i = 0; i < data.Count; i++)
    {
        // columns
        for (int j = 0; j < data[i].Count; j++)
        {

        }
    }

}

I'm unsure about the syntax.

Anyone know how to do that?

Thanks in advance!

2
  • Can you show us what the User table looks like?? What do you want to do with the data?? Commented Feb 18, 2011 at 16:50
  • if all you want is records, you already doing it with your rows for loop, do you also need a loop through all the properties of the User object? Commented Feb 18, 2011 at 16:52

2 Answers 2

5

Why not just like that:

database.dbDataContext db = new database.dbDataContext();

protected void Page_Load(object sender, EventArgs e)
{
    foreach(database.User user in db.Users)
    {
       // do whatever you need to do with your `User` object here.....
       // here, you have an instance of a `User` object - access its properties
       // and methods like you always would on a `User` object....
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

because i didn't know :) Thanks, Marc!
any idea how i can loop though the fields within a row?
@n00b: you don't get a "row" (with columns) back - you get an object back which has properties on it - access them as User.FirstName, User.LastName and so forth. This is an object - not a rows/columns collection! That is of course, assuming I'm right to believe you're using Linq-to-SQL (the dbDataContext seems to indicate that)
i think i got it. i will submit another question in a few minutes :)
3

You're close. You shouldn't need the internal loop. If your code is just this:

database.dbDataContext db = new database.dbDataContext();

protected void Page_Load(object sender, EventArgs e)
{

List<database.User> data = db.Users.ToList();

 for (int i = 0; i < data.Count; i++)
 {
     var a = data[i].Field1;
     var b = data[i].Field2;    
     ...
 }
}

It's a little cleaner to use Marc's version of the loop, but the core is basically that the items in the list are all objects with individual properties, not an array like I assume you expected by having the inner loop there.

Comments

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.