tags:

views:

3030

answers:

6

At the moment I am using one list to store one part of my data, and it's working perfectly in this format:

Item
----------------
Joe Bloggs
George Forman
Peter Pan

Now, I would like to add another line to this list, for it to work like so:

NAME                    EMAIL
------------------------------------------------------
Joe Bloggs              [email protected]
George Forman           [email protected]
Peter Pan               [email protected]

I've tried using this code to create a list within a list, and this code is used in another method in a foreach loop:

// Where List is instantiated
List<List<string>> list2d = new List<List<string>>

...

// Where DataGrid instance is given the list
dg.DataSource = list2d;
dg.DataBind();

...


// In another method, where all people add their names and emails, then are added
// to the two-dimensional list
foreach (People p in ppl.results) {
    list.Add(results.name);
    list.Add(results.email);
    list2d.Add(list);
}

When I run this, I get this result:

Capacity Count 
----------------
16       16 
16       16 
16       16
...      ...

Where am I going wrong here. How can I get the output I desire with the code I am using right now?

A: 

Please show more of your code.

If that last piece of code declares and initializes the list variable outside the loop you're basically reusing the same list object, thus adding everything into one list.

Also show where .Capacity and .Count comes into play, how did you get those values?

Lasse V. Karlsen
Then you need to show us your code. If you can't make heads or tails of your own code, we can't either unless you post it.
Lasse V. Karlsen
+1  A: 

Where does the variable results come from?

This block:

foreach (People p in ppl.results) {
    list.Add(results.name);
    list.Add(results.email);
    list2d.Add(list);
}

Should probably read more like:

foreach (People p in ppl.results) {
    var list = new List<string>();
    list.Add(p.name);
    list.Add(p.email);
    list2d.Add(list);
}
Winston Smith
+8  A: 

Why don't you use a List<People> instead of a List<List<string>> ?

Thomas Levesque
Beat me to it.
JTA
haha me too :-)
Mark Redman
I was about to say that it wouldn't work for me, then I changed my DataGrid variable and now I feel like an idiot. Thank you!
EnderMB
+1  A: 

You should use list of people object or a hashtable.

Nakul Chaudhary
+2  A: 

Highly recommend something more like this:

public class Person {
    public string Name {get; set;}
    public string Email {get; set;}
}

var people = new List<Person>();

Easier to read, easy to code.

Sailing Judo
A: 

Why don't you use a List as Thomas Levesque suggested or just use a DataTable? Using something like List> to store data with a flat hierarchy seems odd to me. You would never put an array into an array, would you?

dkson